Search code examples
rubyactiverecordprotector

How to restrict model based on association using Protector?


Taken from: https://github.com/inossidabile/protector/issues/10

I want to be able to set permissions based on a joining table.

so...

Post.restrict!(current_user).joins(:category)

In this situation the current user doesn't have direct access to category but can get category through Post. How would I accomplish this? It's applying the default category scope and I don't see a way to make it conditional based on the joining table.


Solution

  • Please read this carefully: https://github.com/inossidabile/protector#self-aware-conditions. As you might see, you can accept second parameter to the restriction block. There, inside, you can get any its property or any nested association. So in your case it could be something like:

    protect do |user, post|
      if post.try(:category) && post.category.anything == 'foobar'
        # Whatever you want to allow or disallow here
      end
    end