Search code examples
ruby-on-railsdeclarative-authorization

Declarative authorization - allow editing others comments left in your article?


I'm following Ryan Bates' declarative authorization railscast. I'm trying to add functionality for author of a particular article to be able to edit comments left in his article, regardless of if he is the owner or not. I tried doing it, but couldn't get it to work.

  role :author do
    has_permission_on :articles, :to => [:new, :create]
    has_permission_on :articles, :to => [:edit, :update, :show] do
      if_attribute :user => is { user }
    end
    **has_permission_on :comments, :to => [:edit, :update] do
      if_attribute :article_id => is { user }
    end**
  end

How do I modify the has_permission on comments line to allow user to edit comments if they are left in his article only?

Thanks


Solution

  • In order to allow a user to edit the comments that are published in his/her articles, the rule should looks like:

    role :author do
      [...]
    
      has_permission_on :comments, :to => [:edit, :update] do
        if_attribute :article_id => is_in { user.article_ids }
      end
    end
    

    Please, notice the change of is by is_in

    Optionally, you may change the user.article_ids by user.articles.collect{|a| a.id}.uniq