How to Add Roles to the User Model in Rails 5
In this guide we'll walk through the next set of installation instructions and update the User model so that users can have a specific role. This is how the authorization engine will know what permissions a user has on the website.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Now that we have our petergate installation complete, we need to actually configure it to work with our application. Moving down the list of Isaac's instructions, you can see we have a prerequisite, we don't really have to worry about it because this is what we already did. This gets us into the conversation on why it's important to follow many of the rails standard conventions. Many developers, like Isaac, build some very helpful methods for when we follow rails best practices. For example, he says to make sure that your user model is defined in app/models/user.rb and is called user. He says if you do that then you already have access to all of these methods. These are the ones that his gem allows us to interact with.

We need to install our system, by running his generator. If a copy of this code and switch into the terminal we can run this.

  • rails g petergate:install

Let's take a look and see exactly what this did for us. You can see that insert means that there is some code inserted in our user file and this create, means that an actual file was created.

Switch into Sublime Text, open user.rb and you can see that we have all of this code added by the generator gem. It has petergate roles. It says the role user is added by default and shouldn't be included in this list. The root admin can access any page regardless of access settings. Use with caution. That means root admin is always going to have access to everything. If you wanted to allow other people to write on your blog, we would create another set of rules that would make that possible. By default, I think this is going to give us what we need, we have the ability to have an admin and we have editor..

The userer role that's created by default is probably going to be what we need from a comment point of view. Remember, the only reason we really have a user model is so we can allow users to make comments on our blog posts.

Open up db/migratet and open up the migration file. You can see the migration has created a role and it has

  • :users
  • :roles
  • :string

Come back to the terminal and run rails db:migrate

Switching back, go to the schema file. If I go down to users we can see that we have roles right here.

  • git status
  • git add .
  • git commit -m "Added installation requirements for petergate"
  • git push origin authorization

If we come to pivotal tracker, we have configured the gem. In the next guide, we're going to talk about how we can actually implement the code that is going to enable this.

Resources