Pundit: Allow multiple scopes per model

Created on 25 Nov 2014  路  5Comments  路  Source: varvet/pundit

I was wondering how I should deal with having multiple scopes to authorise against. Performance-wise it doesn't make too much sense to iterate over the collection and retrieve related associations per collection item, rather I would like to use a scope, and perhaps even combine different scopes.

For example: for the index and show actions we rely on the policy's scope - but sometimes it might be necessary to scope to a different context.

What would be one/the recommended approach here?

Most helpful comment

You could add your own custom method to the scope class and then call it using code similar to this:

def index
  @posts = PostPolicy::Scope.new(current_user, Post).your_custom_scope_method
end

Refer to https://github.com/elabs/pundit#scopes for information on how the Scope class is structured in a policy.

All 5 comments

You could add your own custom method to the scope class and then call it using code similar to this:

def index
  @posts = PostPolicy::Scope.new(current_user, Post).your_custom_scope_method
end

Refer to https://github.com/elabs/pundit#scopes for information on how the Scope class is structured in a policy.

Thanks Daryl, that's the recommended approach.

For brevity of code, this could be deferred to the concern, right?

I don't see any reason why it couldn't. However, without seeing what your trying to do its hard to say if it would be a good idea or a code smell.

Looking at the API, it feels like the way to go is to define a second scope and to call it like this :

policy_scope(Post, policy_scope_class: PostPolicy::CustomScope)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ucarion picture ucarion  路  4Comments

DannyBen picture DannyBen  路  6Comments

epinault picture epinault  路  6Comments

dowi picture dowi  路  4Comments

chevinbrown picture chevinbrown  路  4Comments