简体   繁体   English

Rails-为多态关联中的父级指定has_many

[英]Rails - specifying has_many for a parent in polymorphic association

I currently have some models: User, Dealer, Sale and Role. 我目前有一些模型:用户,经销商,销售和角色。 Role has a polymorphic belongs_to relationship with Dealer and Sale, and belongs_to User (see code below). 角色与经销商和销售,以及与用户之间具有多态的belongs_to关系(请参见下面的代码)。

My query is this: how can I specify a has_many :dealers, :through => :roles relationship on User for Dealer and Sale? 我的查询是这样的:我如何在经销商和销售用户上指定has_many :dealers, :through => :roles关系? The role model that the User model would be associating through belongs_to either a Dealer or a Sale, and as such the relationship in this format does not work. 角色模型,该模型的用户会通过关联或者 belongs_to的经销商或销售,并在此格式等的关系不起作用。

class User < ActiveRecord::Base
  has_many :roles
  has_many :sales, :through => :roles
  has_many :appraisals, :through => :roles
  has_many :dealers, :through => :roles
end

class Dealer < ActiveRecord::Base
  has_many :roles, :as => :role_originator
  has_many :users, :through => :roles
end

class Sale < ActiveRecord::Base
  has_many :roles, :as => :role_originator
  has_many :users, :through => :roles
end

class Role < ActiveRecord::Base
  belongs_to :role_type
  belongs_to :user
  belongs_to :role_originator, :polymorphic => true
end

Would appreciate any assistance here. 希望在这里提供任何帮助。

发现:source选项后,我能够解决此问题-参见http://guides.rubyonrails.org/association_basics.html#has_many-association-reference (第4.3.2.20部分)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM