Rails has_many通过多个外键

时间:2018-01-15 10:29:52

标签: ruby-on-rails ruby activerecord

鉴于此:

class House < ApplicationRecord
  has_many :parents
  has_many :children, through: :parents
end

class Parent < ApplicationRecord
  belongs_to :house
  has_many :children, ->(parent) { unscope(:where).where("mother_id = :id OR father_id = :id", id: parent.id) }
end

class Child < ApplicationRecord
  belongs_to :mother, class_name: 'Parent'
  belongs_to :father, class_name: 'Parent'
end

我试图这样做:

Parent.last.children.count # WORKS
House.last.parents.count # WORKS
House.last.children.count # DOESN'T WORK

no such column: children.parent_id: SELECT COUNT(*) FROM "children" INNER JOIN "parents" ON "children"."parent_id" = "parents"."id" WHERE (mother_id = 1 OR father_id = 1)

有没有办法解决has_many :children, through: :parents?它应该将子项返回为ActiveRecord::Associations::CollectionProxy(而不是Array)。或许有些聪明的人加入?

1 个答案:

答案 0 :(得分:3)

house.rb中的has_many :children中的默认联接位于子表和父表之间,具体取决于不存在的parent_id列。

所以你需要覆盖它:所以house.rb应该如下所示。

class House < ApplicationRecord
  has_many :parents
  has_many :children, -> { unscope(:joins).joins('INNER JOIN ON children.father_id = parents.id OR children.mother_id = parents.id') }, through: :parents
end