ruby-on-rails - Rails has_many 通过多个外键

标签 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)的形式返回 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/

相关文章:

ruby-on-rails - Heroku 登录 windows 10

ruby-on-rails - Rails中的自定义错误页面?

ruby-on-rails - Rails 控制台困惑

mysql - Rails 使用 ActiveRecord 乘以 afcolumn 的值

ruby-on-rails - Rails 预览更新关联而不保存到数据库

ruby - 按组大小排列的 Active Record 顺序

ruby-on-rails - 如何使用 postgres 和 ActiveRecord 检索所有重复的电子邮件

ruby-on-rails - 如何使用Rails连接到PostgreSQL容器

ruby - 无论如何我可以使用 if else inside ruby​​ case..end

ruby-on-rails - 从 Rails 5.2 迁移到 Rails 6.0 后,部署实例中随机出现 ActiveRecord::ConnectionNotEstablished