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?
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)
Most helpful comment
You could add your own custom method to the scope class and then call it using code similar to this:
Refer to https://github.com/elabs/pundit#scopes for information on how the Scope class is structured in a policy.