CanCan: limiting a user's ability to set certain model attributes based on their role

后端 未结 4 1642
耶瑟儿~
耶瑟儿~ 2020-12-29 06:10

I have a Post model with a :published attribute (boolean) and a User model with a role attribute (st

4条回答
  •  星月不相逢
    2020-12-29 06:49

    There is a way, I did something like this in my project. But CanCan is not entirely the answer. What you need to do is make attr_accessible in your model dynamic based on user role, so if you're an admin, then you're allowed to update the published field. If not, then giving the field a new value simply won't take when the model saves.

    Railscasts comes to the rescue once again: http://railscasts.com/episodes/237-dynamic-attr-accessible

    Following getting the backend part of that implemented, then you can do something about the frontend form by wrapping the publish field in the View with a roles check or something to show or hide the field based on the user. Rough example of my implementation...

    <% if current_user.roles.where(:name => ['Administrator','Editor']).present? %>
        <%= f.label :display_name %>
        <%= f.text_field :display_name %>
    <% end %>
    

提交回复
热议问题