Adding roles to restful_authentication

I am using the restful_authentication plugin, and I wanted to add some roles. To do so, I did the following:

1. Installed role_requirement also at github role_requirement
2. script/generate roles Role User
3. rake db:migrate
4. Created some views to manage the roles role_requirement views layouts
5. Added the roles to my user create and sessions (user) edit views/actions from restful_authentication

All the code you need to add roles to restful_authentication. Make sure you add the following just at the top of your update and create actions for your users. This is what allows you to add roles to the user.

params[:user][:role_ids] ||= []

IMPORTANT: I was getting an error: Can’t mass assign these protected attributes: role_ids when first trying to use my edit and new user form. The role_ids would not save within the has_and_belongs_to_many table roles_users. I found the answer on a russian site for how to fix the Can’t mass assign these protected attributes: role_ids error.

Once you translate it you’ll see that you need to add the following to your user.rb model.

  # needed this to fix Can't mass assign these protected attributes: role_ids
  # from http://rubyclub.com.ua/messages/show/1324
  attr_accessible :role_ids

Also, here’s how to call the role_requirement has_role? helper method from the view.

<% if current_user.has_role?("admin") %>
  -- stuff --
<% end %>

Other useful links regarding roles with role_requirement and attachment_fu
- restful_authentication role_requirements helper
- Originally, I thought this was my problem, but it wasn’t
- This post had a similar problem with mass-assignl, but didn’t really offer a solution - more of a concept I didn’t quite undertand - being a rails noob and all.

Comments

  1. Les | September 28, 2008

    Scott, thanks for this - it really helps clear some of the role based stuff up for me.

    If I was to need to set a role by default - would you have any tips for what to add and where? I’m having a brain freeze on it! What does this line mean:

    params[:user][:role_ids] ||= []

    ?

    Thanks

    L

  2. John Yerhot | October 22, 2008

    I was getting WARNING: Can’t mass-assign these protected attributes: while using attachment_fu and this helped out a lot.

    Cheeers!