使用 Rails 包括对儿童的条件 [英] Using Rails includes with conditions on children
问题描述
我有一个模型 Parent
有很多孩子 Child
.我想获取所有 Parent 模型并显示 Parent 的每个 Child
.据我所知,这是 Rails 的 includes
方法的经典用例.
I have a model Parent
that has many children Child
. I want to get all Parent models and show every Child
of the Parent as well. This is a classic use case for Rails' includes
method, as far as I can tell.
但是,如果不将父模型限制为有子模型的模型,我无法让 Rails 向子模型添加条件.
However, I can't get Rails to add conditions to the child models without limiting the Parent models to those that have children.
例如,这仅输出有孩子的父母:
For example, this only outputs parents that have children:
Parent.includes(:children).where(children: {age: 10}).each do |parent|
# output parent info
parent.children.where("age = 10").each do |child|
#output child info
end
end
我查看了 Rails 包含条件,但似乎我有与问题的 OP 相同的麻烦,接受的答案的任何部分都不能解决它(它要么只有一些父母,要么求助于多个查询).
I've looked at Rails includes with conditions but it seems like I'm having the same trouble as the question's OP and neither part of the accepted answer doesn't solve it (it either has only some parents, or resorts to multiple queries).
推荐答案
您需要使用<代码>左加入.
Parent.joins("LEFT JOIN children ON parent.id = children.parent_id")
.where("parent.age = 10 AND children.age = 10")
.select("parent.*, children.*")
如果您想从 parent
表中选择在 children
表中可能有也可能没有相应行的行,您可以使用 LEFT JOIN代码> 子句.如果
children
表中没有匹配的行,children
表中列的值将替换为 NULL
值.
If you want to select rows from the parent
table which may or may not have corresponding rows in the children
table, you use the LEFT JOIN
clause. In case there is no matching row in the children
table, the values of the columns in the children
table are substituted by the NULL
values.
这篇关于使用 Rails 包括对儿童的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!