Access Session Settings in a Pundit Policy

It seems that the Pundit policy does not have access to the session settings. Because constructs do not reconnect the session as a valid variable or method. Is there a way to access the session or other parameters?

class MyModelPolicy def create? @contructs = Construct.where(['id = ?', session[:construct_id]]).all end end 
+6
source share
1 answer

I am the author of Pundit. Policies by default have access only to the current user and to the entry for which you are checking permissions.

You can use the context template defined in Pundit docs . Start by creating a user context class in the app/model directory, which takes all the contextual parameters you need, in this case session .

 class UserContext attr_reader :user, :session def initialize(user, session) @user = user @session = session end end 

You can then override the user record used by pundit with an instance of your UserContext class.

 class ApplicationController include Pundit def pundit_user UserContext.new(current_user, session) end end 

Complete the application policy setting. If you want to stay in line with old policies, delegate these methods to the context.

 class ApplicationPolicy attr_reader :context, :user, :session def initialize(context, record) @context = context @record = record end delegate :user, to: :context delegate :session, to: :context ... end 

Now you can access session inside your policies.

+9
source

Source: https://habr.com/ru/post/959280/