首页 > 解决方案 > 刺激反射访问应用程序控制器变量

问题描述

我使用在应用程序控制器中声明的这个实例变量(@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 

标签: ruby-on-railsstimulusjsstimulus-reflex

解决方案


没有直接的方法可以访问 ApplicationController 的方法或 instance_variables,因为它只会在您的反射之后被实例化。

但是您可以ApplicationReflexbefore_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查找身份验证。

当然,您也可以将此方法提取到关注点或模块中,这样您就只有一个实现。


推荐阅读