Skip to content
E. Lynette Rayle edited this page May 3, 2022 · 1 revision

NOTE: All example run in rails console unless otherwise noted.

Create Admin role if it doesn't already exist

Check for admin role

Role.all

If the result includes something like...

=> [#<Role:0x00007fb0b7e5d480 id: 1, name: "admin">]

... then the admin role already exists. OTHERWISE, create the admin role.

Get an instance of the admin role if it exists

admin_role = Role.find(1)

Substitute the actual "admin" id for 1 from the list of roles.

Create admin role if it doesn't exist

admin_role = Role.new(name: 'admin')

Add the user to the role

Get an instance of the user

user = User.find_by(email: "user@example.com")

Add the user to the admin role

user.roles << admin_role

Verify the role was added...

user.roles
=> [#<Role:0x00007fb0b76fd690 id: 1, name: "admin">]