Stimulus Reflex access Application Controller variable

692 views Asked by At

I use this Instance variable (@profile) declared in the Application Controller to check if the current user has rights to access the 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

How can I access the same @profile variable in the Reflex action? Otherwise, any user could change the DOM and edit the Id field.

class ItemGroupReflex < ApplicationReflex
   def state
      Post.find_by(id: element.dataset[:id], profile: @profile).update(state: 'enabled')
  end
end 
1

There are 1 answers

0
Roland Studer On BEST ANSWER

There is no direct way of accessing methods or instance_variables of you ApplicationController, as it will only be instantiated after your reflex.

But you can create the very same method in your ApplicationReflex in a before_reflex callback:

# 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

To have access to your current_user make sure it is available on the application_controller/connection, look for authentication in the docs.

You could of course also extract this method into a concern or a module so you only have one implementation.