簡體   English   中英

Rails4中的多態關聯

[英]Polymorphic association in rails4

我正在按照本教程http://blog.endpoint.com/2012/01/ruby-on-rails-rights-attributes.html設置我的rails4應用程序的授權機制。

我已經創建了數據模型,但是不管理(從控制台)(通過all_rights方法)獲取用戶的權限。

在用戶模型中,由於權限是通過RightAssignment而不是直接從User獲得的,因此User對象如何調用“ self.rights”?

我的模特:

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

任何想法 ?

您可以使用: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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM