Checking Roles in Views Using RoleRequirement

By eric

One of the rails projects I am working on is using the RoleRequirement plugin. This is a great plugin for seamless integration of roles into the controller level, but there wasn’t really much documentation on integrating this into the views themselves. So I figured I would put this little gem out there which has done wonders for the DRYness and cleanliness of my code.

For instance, the code below checks whether or not the current user has the admin role. If they do, it prints the admin menu (in my case I use a partial for this).

< % if current_user.has_role?('admin') %>
<!-- Begin Admin Panel -->
< %= render :partial => '/layouts/admin' %>
<!-- End Admin Panel -->
< % end %>

The great thing is that (although it might be a little unclean), you can chain some conditionals here to show the appropriate menu items based on a users role(s). This is powerful because a user< ->role relationship is a HABTM (Has And Belongs To Many) relationship.

Follow My Travels

Buy My Book


  • 2020
  • 2019
  • 2017
  • 2014
  • 2013
  • 2012
  • 2011
  • 2010
  • 2009
  • 2008
  • 2007
  • 2006

New Posts By Email