Search code examples
ruby-on-rails-4deviserails-adminpunditcancancan

Field level permissions using CanCanCan or Pundit


I am currently using Rails 4.1.14 with CanCanCan 1.13.1 and defined granular permissions on model/record level. Admins can manage all articles but users can edit only articles they authored.

To prevent regular users for editing specific fields I make fields visible in rails_admin depending on role.

visible do 
  bindings[:object].id == bindings[:view].current_user.roles.include? :admin
end

I am also using https://github.com/aasm/aasm gem and created custom actions so user can move records into new states.

But what I really want is to enable field level permissions depending on user's role / record. I can't find any docs on CanCanCan or https://github.com/elabs/pundit pages.

Does anyone have experience with that?


Solution

  • You mean that an admin should be allowed to edit all fields of a record, but an editor is only allowed to change the fields x and y?

    Yes, this is possible in pundit, since it integrates with strong parameters (which you should be using anyway). There's also an example in the pundit readme (see: Strong parameters). I simplified example from the readme:

    # post_policy.rb
    def permitted_attributes
      if user.admin?
      [:title, :body, :tag_list]
    else
      [:tag_list]
    end
    
    # posts_controller.rb
    @post.update_attributes(permitted_attributes(@post))
    

    the permitted_attributes helper in the controller is provided by pundit and automagically calls the permitted_attributes method of the infered policy.