【发布时间】:2021-09-25 06:40:57
【问题描述】:
rails 控制台中的预期结果,father.children 和 mother.children 应该返回同一组对象:
father = User.first
father.children
=> #<ActiveRecord::Associations::CollectionProxy [#<User id: 3, name: "son", father_id: 1, mother_id: 2>, #<User id: 4, name: "daughter", father_id: 1, mother_id: 2>]>
mother = User.find(2)
mother.children
=> #<ActiveRecord::Associations::CollectionProxy [#<User id: 3, name: "son", father_id: 1, mother_id: 2>, #<User id: 4, name: "daughter", father_id: 1, mother_id: 2>]>
这是我现在在 User.rb 模型中的关联。如果我执行father.children,它将返回预期结果,因为foreign_key 指的是father_id。但它不适用于mother.children,因为它不引用mother_id。
has_many :children, foreign_key: "father_id", class_name: "User"
belongs_to :mother, class_name: "User", optional: true
belongs_to :father, class_name: "User", optional: true
我有什么办法吗
foreign key: "father_id" OR "mother_id"
我也尝试在关联中进行查询,但似乎无法理解它。
has_many :children, -> { where("father_id = id OR mother_id = id") }, class_name: "User"
【问题讨论】:
-
在关联中使用查询时遇到什么问题?
-
我认为这应该可行:
has_many :children, ->(user) { where("father_id = :id OR mother_id = :id", id: user.id) }, class_name: "User" -
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."user_id" = ? AND (father_id = 1 OR mother_id = 1) /* loading for inspect */ LIMIT ? [["user_id", 1], ["LIMIT", 11]]这是返回的内容。问题是当我使用查询时,即使我没有在查询中指定,它也会自动执行WHERE "users"."user_id" -
按照下面的答案建议添加 unscope 应该可以解决问题。
-
是的,
has_many :children, ->(user) { unscope(:where).where("father_id = :id OR mother_id = :id", id: user.id) }, class_name: "User"收到了,非常感谢!
标签: ruby-on-rails ruby database foreign-keys associations