【问题标题】:Finding a user is Admin or Not with Decalarative Authorization使用声明性授权查找用户是否为管理员
【发布时间】:2013-04-27 17:45:15
【问题描述】:

我已经在我的博客应用中实现了声明式授权。现在,我为管理员、经过身份验证的用户和来宾用户分别设置了三种布局。所以我需要检查在特定时间使用该应用程序的用户类型。我们有用户模型、角色模型和分配模型。

用户.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

作业.rb

class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
end

角色.rb

class Role < ActiveRecord::Base
  attr_accessible :name
  has_many :assignments
  has_many :users, :through => :assignments
end

有什么办法吗?

【问题讨论】:

  • 您的模型到底长什么样?协会?一个用户是否总是只有一个角色?
  • 是的。我会更新问题。

标签: ruby-on-rails admin declarative-authorization


【解决方案1】:

您可以使用此 gem 简化您的结构: https://github.com/platform45/easy_roles 按照 github 上的说明修改你的模型,就像那里描述的那样。 这真的很容易,只需几个步骤。你只需要你的用户模型,就是这样!

另外,我会推荐康康舞宝石 (https://github.com/ryanb/cancan)。

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

【讨论】:

  • 当前模型配置没有选项?
  • 当然有..但我认为它会变得有点棘手。您可以为每个角色定义一个返回 true 或 false 的方法,例如 def admin? current_user.roles.include?("the admin id") end。其他所有角色都类似。您还可以生成泛型方法,例如 def has_roles?(roles_as_array) current_user.roles.include?(roles_as_array with some find magic)。你明白我的意思有点棘手吗? :)
猜你喜欢
  • 1970-01-01
  • 2014-07-19
  • 2011-10-24
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-06
相关资源
最近更新 更多