简体   繁体   English

Rails4中的多态关联

[英]Polymorphic association in rails4

I'm following this tutorial http://blog.endpoint.com/2012/01/ruby-on-rails-rights-attributes.html to setup an authorization mechanism for my rails4 application. 我正在按照本教程http://blog.endpoint.com/2012/01/ruby-on-rails-rights-attributes.html设置我的rails4应用程序的授权机制。

I have created the data model but do not manage (from the console) to get the rights (via the all_rights method) of a user. 我已经创建了数据模型,但是不管理(从控制台)(通过all_rights方法)获取用户的权限。

In the user model, how can the User object call "self.rights" as the rights are available through RightAssignment and not directly from User ? 在用户模型中,由于权限是通过RightAssignment而不是直接从User获得的,因此User对象如何调用“ self.rights”?

My models: 我的模特:

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

Any idea ? 任何想法 ?

you can use :through 您可以使用: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