ruby-on-rails - Rails has_many 通过为多种类型使用 source 和 source_type 别名

标签 ruby-on-rails activerecord associations has-many-through 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?这对 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

最佳答案

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

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

关于ruby-on-rails - Rails has_many 通过为多种类型使用 source 和 source_type 别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17541277/

相关文章:

ruby-on-rails - bundle 安装错误 "invalid byte sequence in US-ASCII (ArgumentError)"

ruby-on-rails - 如何从克隆的 ActiveRecord 模型中删除只读状态?

ruby-on-rails - rails : How to get enum value for joined table?

uml - 什么是 UML 中的一元关联

php - 与 Doctrine PHP 的关联

mysql - 将关联从一对多更改为多对多

ruby-on-rails - XPath 或 CSS 解析速度更快(对于 HTML 文件上的 Nokogiri)?

ruby-on-rails - Cucumber - 启用默认驱动程序(selenium)时数据库清理器不工作

mysql - Rails 虚拟属性与 ActiveRecord

winXP 上的 python 版本