Checking Roles in Views Using RoleRequirement

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 -->
<h2>admin</h2>
< %= 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.

Posted in Rails. Tags: . 2 Comments »
  • http://www.mrit.co.za Grant

    Do you have a tutorial on the integration of role requirement? I am new to rails and I am really struggling to find info on how to implement it. Any help would be great.

    Regards,

    G

  • http://eric.lubow.org/ eric

    I actually just unimplemented RoleRequirement because I found it unsuited for my needs (although it does do many good things in its own right). I used the documentation on the RoleRequirement site (http://code.google.com/p/rolerequirement/). It was easy enough to follow. As with any major change to my project, I first created a branch to test in to ensure proper deployment.

    If you try installing it using the instructions on the Google site and still have problems, let me know and I will throw together a quick HOWTO on it.