-1

I'm looking for the best way, in ruby on rails 4.2, to create and manage users role with differente attributes and permissions.

I don't want to create one table for each users roles, i have some solution with enum or some gem like cancan or rolify but i want to know what is the best way to improve performance, respect the agreements, and write strong code and architecture.

Anyone can help me ?

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
T1djani
  • 27
  • 1
  • 9

1 Answers1

1

It's not Cancancan or Rolify or enum, but Rolify + Cancancan or Enum + Cancancan.

Authorization gems such as Cancancan or Pundit (which I prefer) are used for managing what your users can do, based on their role. So Roles and Authorization aren't opposed, they normally complement each other.

Rolify + Pundit is a nice solution and will give your users the ability to have several roles.

For single-role-based authorization, then Enum is more straightforward. It's used especially (but not only) by apps having a hierarchy in their roles, like member, moderator, admin.

To get roles based on Enum under 5 minutes, first add a role column to users:

class AddRoleToUsers < ActiveRecord::Migration
  def change
    add_column :users, :role, :integer, default: 0 #The default role will be the one set at 0 in user.rb
  end
end

Then, define the roles in user.rb

enum role: { buyer: 0, seller: 1, admin: 2 }

This will directly allow you to do something like current_user.admin?, without writing more code, which is quite convenient and clean.

Yimanei
  • 242
  • 2
  • 8