查找用户是否具有声明性授权的Admin



我已经在我的博客应用程序中实现了声明式授权。现在我有三个布局,分别为Admin, Authenticated User和guest User。我需要检查在特定时间使用应用的用户类型。我们有用户模型,角色模型和分配模型。

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

解决方案吗?

你可以用这个gem来简化你的结构:https://github.com/platform45/easy_roles按照github上的说明修改您的模型。这真的很简单,只需要几步。你只需要你的用户模型,就是这样!

另外,我推荐cancan gem (https://github.com/ryanb/cancan)。

easy_roles和cancan是很好的组合,可以很容易地定义角色和权限!

最新更新