I have implemented declarative authorization in my blog app. Now I have three layouts each for an Admin, Authenticated User and guest user. So I need to check what type of user is using the app at a particular time. We have User model, Role model and Assignment Model.
User.rb
class User < ActiveRecord::Base
attr_accessible :login, :email, :password, :password_confirmation, :role_ids
has_many :articles
has_many :comments
has_many :assignments
has_many :roles, :through => :assignments
def role_symbols
roles.map do |role|
role.name.underscore.to_sym
end
end
acts_as_authentic do |c|
c.login_field = :login
end
def deliver_password_reset_instructions!
reset_perishable_token!
Notifier.deliver_password_reset_instructions(self)
end
end
Assignment.rb
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
Role.rb
class Role < ActiveRecord::Base
attr_accessible :name
has_many :assignments
has_many :users, :through => :assignments
end
Any solution?
You could simplify your structure with this gem: https://github.com/platform45/easy_roles Follow the instructions on github and modify your models like described there. It is really easy, just a few steps. You just need your user model, and that´s it!
Additionally I would reccomend the cancan gem (https://github.com/ryanb/cancan).
easy_roles and cancan are a good combination to define roles and permissions quite easily!