ruby-on-rails – Rails has_many通过使用source和source_type进行多项类型的别名

所以这里是一个示例类
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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...