I\'m new to rails, and I\'m working on my second rails app.
The app will have different roles for users, but some users will have multiple roles.
Every user of t
You can look for gems Devise and CanCan. This pair is really powerful combination. This makes two models User and Role. In Role you can create new roles, without creating new models for them. Although it creates model Ability, here you can define access rules for roles.
Manual: http://www.tonyamoyal.com/2010/07/28/rails-authentication-with-devise-and-cancan-customizing-devise-controllers/
Here you can find Devise's and CanCan's sources and wikies:
https://github.com/plataformatec/devise
https://github.com/ryanb/cancan
My models looks like this:
Role.rb
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
User.rb
class User < ActiveRecord::Base
has_many :accounts
has_and_belongs_to_many :roles
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :username, :password, :password_confirmation, :remember_me, :role_ids
def role?(role)
return !!self.roles.find_by_name(role.to_s.camelize)
end
end
Ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role? :administrator
can :manage, :all
elsif user.role? :operator
can :read, Account
can :read, Server
elsif user.role? :customer
can :manage, Account
can :read, Server
end
end
end
In the controller you must add only this two lines:
class YourController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource
...
end