所以这里是一个示例类
class Company < ActiveRecord::Base has_many :investments has_many :vc_firms,through: :investments,source: :investor,source_type: 'VentureFirm' has_many :angels,source_type: 'Person' end
@ company.angels和@ company.vc_firms按预期工作.但是,我如何拥有由两种源类型组成的@ company.investors?这将适用于投资表的投资者列上的所有多态?或者可能是使用范围来合并所有source_type的方法?
投资模式如下所示:
class Investment < ActiveRecord::Base belongs_to :investor,polymorphic: true belongs_to :company validates :funding_series,presence: true #,uniqueness: {scope: :company} validates :funded_year,presence: true,numericality: true end
天使通过人物模型相关联
class Person < ActiveRecord::Base has_many :investments,as: :investor end
相关金融机构模范协会:
class FinancialOrganization < ActiveRecord::Base has_many :investments,as: :investor has_many :companies,through: :investments end
解决方法
以前的解决方法是错误的,我误解了一个关系.
Rails不能为您提供跨多态关系的has_many方法.原因是这些实例通过不同的表进行分布(因为它们可能属于不同的模型,可能不在同一个表上).因此,如果您跨越belongs_to多态关系,则必须提供source_type.
话虽如此,假设你可以在投资者这样使用继承:
class Investor < ActiveRecord::Base has_many :investments end class VcFirm < Investor end class Angel < Investor end
您可以从投资中删除多态选项:
class Investment < ActiveRecord::Base belongs_to :investor belongs_to :company ......... end
你将能够跨越这个关系并将其作为范围:
class Company < ActiveRecord::Base has_many :investments has_many :investors,through :investments has_many :vc_firms,conditions: => { :investors => { :type => 'VcFirm'} } has_many :angels,conditions: => { :investors => { :type => 'Angel'} } end