简体   繁体   中英

Rails cancancan how to limit user privilige in view when there are lots of roles?

Rails cancancan how to limit user privilige in view when there are lots of roles? And each role has multiple priviliges. For example, in my rails app there are about 50 view files, such as article.html.erb, product.html.erb, comment.html.erb, order.html.erb,...,and so on. What I have to do is adding priviliges in every .html.erb file:

 <% if can? :update, @article %>
    <%= link_to "Edit", edit_article_path(@article) %>
 <% end %>
...
 <% if can? :update, @product %>
    <%= link_to "Edit", edit_product_path(@product) %>
 <% end %>

So if in this way, I have to do a lot of tedious works. When the requestment is changed, I have to modify multiple .html.erb files.

So my question is, if there is any methods that I can accept to avoid this way? Such as using a global tag to control all the views to display or not display the "Edit","Destroy" methods?

You can use layouts in rails .
Create a partial view, say _user_privileges.html.erb inside layouts folder in app/views and write the code related to privileges there. Now in each of the other view files you can use <%= render 'layouts/user_privileges' %> . So now you can use a single file to change the privileges.

_user_privileges.html.erb

<% if can? :update, @article %>
    <%= link_to "Edit", edit_article_path(@article) %>
 <% end %>
...
 <% if can? :update, @product %>
    <%= link_to "Edit", edit_product_path(@product) %>
 <% end %>

article.html.erb, product.html.erb, comment.html.erb, order.html.erb etc.

...
<%= render 'layouts/user_privileges'  %>
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM