11

所以这是一个示例类

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?这适用于 Investments 表的 Investor 列上的所有多态性吗?或者可能是使用范围合并所有 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
4

2 回答 2

14

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

Rails 无法为您提供跨越多态关系的 has_many 方法。原因是实例分布在不同的表中(因为它们可以属于不同的模型,这些模型可能在同一个表上,也可能不在同一个表上)。因此,如果您跨过 belongs_to 多态关系,则必须提供 source_type。

话虽如此,假设您可以像这样在 Investor 中使用继承:

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
于 2013-07-24T18:19:54.563 回答
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看起来对阅读:sourcevs.很有帮助:source_type

希望能帮助到你!

于 2013-07-29T22:04:06.717 回答