Field Level Permissions Using CanCanCan or Pundit

I am currently using Rails 4.1.14 with CanCanCan 1.13.1 and specific granular permissions at the model / record level. Admins can manage all the articles, but users can only edit the articles they created.

To prevent regular users from editing certain fields, I make the fields visible in rails_admin depending on the role.

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

I also use https://github.com/aasm/aasm gem and created custom actions so that the user can move records to new states.

But I really want to enable field level permissions depending on the role / user record. I can not find any documents on CanCanCan or https://github.com/elabs/pundit pages .

Does anyone have any experience?

+4
source share
1 answer

You mean that the administrator should be allowed to edit all fields of the record, but the editor should be allowed to change only the fields x and y?

Yes, this is possible in pundit, as it integrates with strong parameters (which you should use anyway). There is also an example in the pundit readme (see: Strong Options). I simplified the example from 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))

permitted_attributes pundit permitted_attributes , .

+4

Source: https://habr.com/ru/post/1624531/


All Articles