Giving your user model a role

henning-koch edited this page Nov 3, 2010 · 12 revisions

To give your user model an Aegis role, use the has_role macro:

class User < ActiveRecord::Base
  has_role
end

Instances of that User class can now be checked for permission like user.may_do_action?.

By default, Aegis looks for the role name in a method role_name. The return value should match a role defined in your Permissions class.

Storing the role name in the database

While the role_name property does not have to be persistent, in most cases it is convenient to add a string column role_name to your users table:

class AddRoleNameToUser < ActiveRecord::Migration

  def self.up
    add_column :users, :role_name, :string
  end

  def self.down
    remove_column :users, :role_name
  end

end

Options

has_role comes with a number of optional parameters:

  • :default: The default role name given to new User instances. Default is nil.
  • :permissions: The name of your permissions class as string or Class object. Default is 'Permissions'.

Validate that a user has a role

You probably want to have the role_name column set for all User records. To validate this you can say:

class User < ActiveRecord::Base
  has_role
  validates_role
end

You can change the validation error message using the :message parameter. The default uses the same message as validates_inclusion_of.