Hiding Elements in the View Based on Pundit Permissions
In this guide we are going to remove the Edit link for those posts that have a status of approved. Thankfully this is quite easy to implement since we're using Pundit to manage our permission structure.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In the previous guide we created labels for our status elements. Even though it's working, I'm not happy with the user interface. Mainly because I think users shouldn't be allowed to click the edit link at all, if the post has an approved status (even if it will block them). A good user experience policy is to not show a user an elements that they don't have access to.

In this guide we are going to remove the Edit link for those posts that have a status of approved. Thankfully this is quite easy to implement since we're using Pundit to manage our permission structure.

To get started we are going to use a method called policy provided by pundit that's available to our views. Open _post.html.erb and add this policy method call to the edit line.

<!-- app/views/posts/_post.html.erb -->

<%= link_to 'Edit', edit_post_path(post), id: "edit_#{post.id}" if policy(post).update? %>

In this method, we are passing the post as an argument into the policy method and we are asking Rails to display the Edit link only if the update method returns a true value. If you remember, we've already implemented the update method in our post_policy.rb file. So, this is the only change we have to make.

Essentially this simply means that our application will render the link if, and only if the user has access to edit the record. This is a great way of implementing the feature because it allows us to control the source of the behavior from a single method. This is as opposed to trying to manipulate the view manually, which would force us to change the application in multiple locations if we ever want to alter this feature.

If you refresh the browser, this is what you'll see:

large

Resources