鉴于此:
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
)的形式返回 child 。也许一些聪明的加入?
最佳答案
在 house.rb 中 has_many :children
中的默认连接是在 children 和 parents 表之间,具体取决于不存在的 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
关于ruby-on-rails - Rails has_many 通过多个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48261117/