【问题标题】:Stimulus Reflex access Application Controller variable刺激反射访问应用程序控制器变量
【发布时间】:2021-03-06 16:53:12
【问题描述】:

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


    【解决方案1】:

    没有直接访问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 上可用,请查找 authentication in the docs

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

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 2023-01-01
      • 1970-01-01
      • 2021-01-20
      • 2020-11-01
      • 2022-11-18
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多