ruby-on-rails - 刺激反射访问应用程序控制器变量
问题描述
我使用在应用程序控制器中声明的这个实例变量(@profile)来检查当前用户是否有权访问 params[:profile_id]
class ApplicationController < ActionController::Base
before_action :set_profile
def set_profile
if params[:profile_id].present? && current_user
@profile = Profile.joins(:ownerships).find_by(profiles: {id: params[:profile_id]}, ownerships: {user: current_user})
end
end
end
如何在 Reflex 操作中访问相同的 @profile 变量?否则,任何用户都可以更改 DOM 并编辑 Id 字段。
class ItemGroupReflex < ApplicationReflex
def state
Post.find_by(id: element.dataset[:id], profile: @profile).update(state: 'enabled')
end
end
解决方案
没有直接的方法可以访问 ApplicationController 的方法或 instance_variables,因为它只会在您的反射之后被实例化。
但是您可以ApplicationReflex
在before_reflex
回调中创建完全相同的方法:
# app/reflex/application_reflex.rb
class ApplicationReflex < StimulusReflex::Reflex
before_reflex :set_profile
def set_profile
if params[:profile_id].present? && current_user
@profile = Profile.joins(:ownerships).find_by(profiles: {id: params[:profile_id]}, ownerships: {user: current_user})
end
end
end
要访问您的 current_user 确保它在 上可用,请在文档中application_controller/connection
查找身份验证。
当然,您也可以将此方法提取到关注点或模块中,这样您就只有一个实现。
推荐阅读
- actionscript-3 - 为什么 file.moveTo(newfile, true) 会抛出 #3003 错误?
- gatsby - 无法在 gatsby 上设置十六进制到 rgba 转换
- php - 将自定义图标添加到 Woocommerce 购物车和结帐中的运输选项
- neural-network - Mask R-CNN 实例分割与目标检测
- java - Tomcat 8 托管的 Web 服务:Java 类以 HTML 而非实际文本显示
- c - 为什么 MPI 程序以退出代码 134(信号 6)终止?
- css - CSS,溢出滚动内的动态长度
- react-native - React Native 设备信息模块在 0.61 中失败
- caching - 需要刷新之前访问过的 Gatsby 站点以查看更改
- javascript - JavaScript,JQuery,将 HTML 元素下载为图像(画布到图像)