11

因此,这里是一个示例类导轨的has_many多种类型

class Company < ActiveRecord::Base 
    has_many :investments 
    has_many :vc_firms, through: :investments, source: :investor, source_type: 'VentureFirm' 
    has_many :angels, through: :investments, source: :investor, 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 

天使通过Person模型相关

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 

回答

14

以前的解决方案是错误的,我误解了其中一个关系。

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, through: :investments, source: :investor, conditions: => { :investors => { :type => 'VcFirm'} } 
    has_many :angels, through: :investments, source: :investor, conditions: => { :investors => { :type => 'Angel'} } 
end 
+0

不起作用。以下是错误:ActiveRecord :: HasManyThroughAssociationPolymorphicSourceError:通过关联'公司#投资者'关联多态对象'投资者#投资者'而没有'source_type',不能拥有has_many:。尝试添加'source_type:'投资者''到'has_many:通过'定义。 –

+0

@MichaelKMadison我更正了答案 – polmiro

+0

嗯...然后我不得不将人和金融机构存储在同一张表中,这感觉不对。 –

2

我加到Company类与投资表连接获取所有投资者对于公司的方法:

class Company < ActiveRecord::Base 
    has_many :investments 
    has_many :vc_firms, :through => :investments, :source => :investor, :source_type => 'VcFirm' 
    has_many :angels, :through => :investments, :source => :investor, :source_type => 'Angel' 

    def investors 
    Investor.joins(:investments).where(:investments => {:company_id => id}) 
    end 
end 

http://www.brentmc79.com/posts/polymorphic-many-to-many-associations-in-rails看起来非常有助于对:source:source_type读了。

希望它有帮助!