【问题标题】:Conditional polymorphic association with has many through条件多态关联有很多通过
【发布时间】:2015-11-24 15:11:59
【问题描述】:

我在模型之间有一个棘手的关联结构,我不知道如何实现它。

我有政策,每个政策都有政策参与者。

这些保单参与者可以是个人或公司,并且具有特定类型,例如被保险人或投保人。每个策略都具有每种类型的策略参与者。

到目前为止我所拥有的:

class Policy < ActiveRecord::Base
  has many :policy_participants

  # insuree
  has_one :insuree_participant, -> { insuree }, class_name: 'PolicyParticipant'
  has_one :insuree, through: :policy_participants, -> { where(role: 1) }, source: :participant
end

class PolicyParticipant < ActiveRecord::Base
  belongs_to :policy
  belongs_to :participant, polymorphic: true
  enum role: { insuree: 1, contributor: 2, etc: 3 }
end

class Person < ActiveRecord::Base  # same for Company.rb
  has_many :policy_participations, as: :participant
  has_many :insuree_policy_participations, -> { insuree }, as: :participant
end

在 Rails 控制台中,当我尝试 policy.insuree 时,我收到此错误:

ActiveRecord::HasManyThroughSourceAssociationNotFoundError:在模型 PolicyParticipant 中找不到源关联“insuree”或 :insuree。尝试'has_many :insuree, :through => :policy_participants, :source => '。是政策、参与者、类型、地址、个人还是公司之一?

我想过为个人和公司创建一个父类,但由于只有名称相同,我宁愿避免这样做。

有人可以帮助我吗?

【问题讨论】:

    标签: ruby-on-rails activerecord polymorphism rails-activerecord


    【解决方案1】:

    我认为这条线需要改变

    has_one :insuree, through: :policy_participants, -> { where(role: 1) }, source: :participant
    

    到

    has_one :insuree, -> { where(role: 1) }, through: :policy_participants, source: :participant
    

    lambda(或作用域)必须是 has_one 的第一个参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 2017-09-03
      • 1970-01-01
      • 2014-09-21
      • 2018-01-28
      • 2012-04-29
      相关资源
      最近更新 更多