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.
mysecurity/app/models/user_role.rb (unmodified)
We go ahead and modify the file to link UserRole to User and to Role.
mysecurity/app/models/user_role.rb (modified)
Below we have the User model that was generated by Devise for us.
mysecurity/app/models/user.rb (unmodified)
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!
mysecurity/app/models/user.rb (modified)
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.
mysecurity/config/routes.rb (unmodified)
mysecurity/config/routes.rb (unmodified)
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
_form.htm.erb.
Now our next step is to add the functionality to the view that allows us to assign roles to users.
/users/_role_checkbox.htm.erb
/users/_form.htm.erb
Start the application server using the “rails server” command and navigate to http://localhost:3000/users/new and you should see a screen
similar to the screenshot below.
In Part 5 of this series we will finally pull all of the
functionality together and secure our web application.