【问题标题】:Polymorphic association in rails4rails4中的多态关联
【发布时间】:2014-01-09 16:05:12
【问题描述】:

我正在按照本教程 http://blog.endpoint.com/2012/01/ruby-on-rails-rights-attributes.html 为我的 rails4 应用程序设置授权机制。

我已经创建了数据模型,但没有管理(从控制台)获取用户的权限(通过 all_rights 方法)。

在用户模型中,用户对象如何调用“self.rights”,因为权限是通过 RightAssignment 而不是直接从 User 获得的?

我的模型:

class User < ActiveRecord::Base
  has_many :right_assignments, as: :subject
  has_and_belongs_to_many :groups
  has_and_belongs_to_many :roles

  def all_rights
    rights = [self.rights +
          self.groups.collect { |g| g.allowed_rights } +
          self.roles.collect { |r| r.rights }]
     rights = rights.flatten.uniq.collect { |r| r.action }
     rights
  end
end

class Group < ActiveRecord::Base
  has_many :right_assignments, as: :subject
  has_and_belongs_to_many :users

  def allowed_rights
    self.assignable_rights ? self.rights : []
  end
end

class Role < ActiveRecord::Base
  has_many :right_assignments, as: :subject
  has_and_belongs_to_many :users
end

class RightAssignment < ActiveRecord::Base
  belongs_to :right
  belongs_to :subject, polymorphic: true
end

class Right < ActiveRecord::Base
  has_many :right_assignments
end

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 polymorphism


    【解决方案1】:

    你可以使用:through

    class User < ActiveRecord::Base
      has_many :right_assignments, as: :subject
      has_many :rights, :through => :right_assignments
      has_and_belongs_to_many :groups
      has_and_belongs_to_many :roles
    

    【讨论】:

      猜你喜欢
      • 2016-09-20
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 2015-07-20
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多