刺激反射访问应用程序控制器变量

Stimulus Reflex access Application Controller variable

我使用在应用程序控制器中声明的这个实例变量(@profile)来检查当前用户是否有权访问参数[: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 

无法直接访问方法或 instance_variables 您的 ApplicationController,因为它只会在您反射后实例化。

但是您可以在 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 上可用,查找 authentication in the docs

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