Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Devise - Admin role, model vs attribute

I know how to create an admin role/user : https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-role

What I am wondering though is if there are any advantages or disadvantages to the two options to consider when deciding between them. Can anyone supply any insight on this please?

like image 786
Mr Morphe Avatar asked Nov 04 '13 10:11

Mr Morphe


2 Answers

Let me muddle the water a bit. I prefer to this via a Role table and a join table UserRole. This way I can define more than one role without adding another column/table to db.

class User
  has_many :user_roles
  has_many :roles, :through => :user_roles

  def role?(role)
    role_names.include? role
  end

  def role_names
    @role_names ||= self.roles.map(&:name)
  end

  def role=(role)
    self.roles << Role.find_or_create_by_name(role)
  end
end

class UserRole 
  # integer: user_id, integer: role_id
  belongs_to :user
  belongs_to :role
end

class Role
  # string: name
  has_many :user_roles
  has_many :users, :through => :user_roles
end
like image 67
tihom Avatar answered Oct 23 '22 17:10

tihom


It really depends on what you wish to do with your admin role. The first option, I would say is a bit secure as the admin role is a unique model in itself.

The second option is straightforward and would help you get going with the least effort. However, if your users figure out the boolean variable and a way to set it, any user can become an admin and access areas you don't want them to.

like image 37
rb512 Avatar answered Oct 23 '22 16:10

rb512