Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to hide parts of the view given a user role on Rails 4
    primarykey
    data
    text
    <p>I'm trying to hide parts of my views depending on the User role.</p> <p>So let's say I want only admins to be able to destroy Products. Besides the code in the controller for preventing regular users from destroying records, I would do the following in the view:</p> <pre><code>&lt;% if current_user.admin? %&gt; &lt;%= link_to 'Delete', product, method: :delete %&gt; &lt;% end %&gt; </code></pre> <p>The previous code works, but it's prone to errors of omission, which may cause regular users to see links to actions they are not allowed to execute.</p> <p>Also, if I decide later on that a new role (e.g. "moderator") can delete Products, I would have to find the views that display a delete link and add the logic allowing moderators to see it.</p> <p>And if there are many models that can be deleted only by admin users (e.g. Promotion, User) maitenance of all the ifs would be pretty challenging.</p> <p>Is there a better way of doing it? Maybe using helpers, or something similar? I'm looking for something maybe like this:</p> <pre><code>&lt;%= destroy_link 'Delete', product %&gt; # Only admins can see it &lt;%= edit_link 'Edit', promotion %&gt; # Again, only admins see this link &lt;%= show_link 'Show', comment %&gt; # Everyone sees this one </code></pre> <p>I found these two questions that are similar to mine, but none of them answered my question:</p> <p><a href="https://stackoverflow.com/questions/14076469/show-and-hide-based-on-user-role-in-rails">Show and hide based on user role in rails</a></p> <p><a href="https://stackoverflow.com/questions/4719319/ruby-on-rails-3-hiding-parts-of-the-view">Ruby on Rails (3) hiding parts of the view</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload