how to set role in rails :::: https://altalogy.com/blog/rails-6-user-accounts-with-3-types-of-roles/

 https://altalogy.com/blog/rails-6-user-accounts-with-3-types-of-roles/





Authorization – CanCanCan

We use CanCanCan gem to restrict access to some parts of the app. Whatsmore, we grant different permissions for specific roles. Add to Gemfile:

Run:

Next, use this command to generate ability class:

You can define abilities in app/models/ability.rb. But first, we have to set different roles. It’s up to you how you want to define roles. We will use three roles: superadminsupervisor, and user. We add three boolean columns for each role in the user model. Let’s start by generating migration:

Before we run the migration, let’s edit it. Open db/migrate/xxx_add_roles_to_users.rb and adjust the code:

We’ve defined default values for superadmin and supervisor as a false, and true default value for user_role. Now we can run:

To verify current user’s role, you can use:

Views

To display some elements only for users with a specific role, you can use:

Or you can use CanCanCan abilities:

And in app/model/ability.rb:

Comments

Popular posts from this blog

Rails 7 Features :: Comparison with Rails 6 and Rails 5