[英]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.