加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails has_many通过使用source和source_type进

发布时间:2020-12-17 01:20:42 所属栏目:百科 来源:网络整理
导读:所以这里是一个示例类 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_firm
所以这里是一个示例类
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读