Role management in Rails with rolify gem

Tram Ho

Introduce

Rolify is a gem in Rails used to support the management of Roles in Rails easily and quickly.

It supports the whole scope on a resource object. For example:

Setting

=> bundle install

Using

1. Create Role Model

First, I have to use its generator to set up Rolify. Model Role and User are the default names. However, you can also use a different name depending on your actual project.

The generator will create your Role model, add a migration file, and update your User class with new class methods.

This generator will:

  • Create Role model
  • Create new migration file
  • Update the User model with a new class method

2. Configure resource models

In the models you want to apply the role to, you only need to add the resourcify method as follows:

Create role for User

Create global Role: Role for all resource objects

Create roles for a given resource instance:

Create roles for certain resource classes:

Delete role:

Role queries

Check if the user has global role or not:

Check if the user has a role on that resource instance:

Check if the user has a role on that resource class:

If you create a global role for the user, the gloabl role will override all the roles for the resource:

To check if that user has a specific role for a given resource:

The above are the methods needed to use Roliy, but of course there are other methods as well. For more details, refer to its documentation here.

https://github.com/RolifyCommunity/rolify

Share the news now

Source : Viblo