Ruby on Rails Authentication and Authorization Part 4
Created: 6 April 2012 Modified:
In Part 3 of the series we modified the model and views generated
by the Rails utilities to allow for creating hierarchical roles. In Part 4 we will perform almost the same series of steps to allow us to
assign Roles to Users.
Our first step will be to use Rails to generate a model for your “user_role” linking table.
The generator will build the user_role.rb file as shown below.
We go ahead and modify the file to link UserRole to User and to Role.
Below we have the User model that was generated by Devise for us.
We will modify the user.rb file to add the relationship between User and Role. One difference here is that we need to add “:role_ids” to the
list of accessible attributes. Only those fields of the model passed to “attr_accessible” will be updateable. This message
“WARNING: Can’t mass-assign protected attributes: role_ids” led me to this discovery. Fortunately other developers had been there before me
and had the answers!
Next we will use the Rails generator to build the scaffolding for the user model.
Terminal window in the mysecurity directory
In the following steps I alias devise to use the “user” path and set resources for the users controller in the routes.rb file.
My next step is to copy part of the contents of /devise/registrations/new.html.erb and create the file
/devise/registrations/_user_fields.html.erb. This will allow me to include the fields in the /users/_form.html.erb file giving me one
location to change the fields for three locations where it is used. The three files that need to be modified follow along with the