问题描述
我有以下模型:
class GrandParent < ActiveRecord::Base
has_many :parents
has_many :children, through: :parents
end
class Parent < ActiveRecord::Base
has_many :children
belongs_to :grand_parent
end
class Child < ActiveRecord::Base
belongs_to :parent
end
我想查找所有孩子,其中孩子的grand_parent的值等于TRUE,但是我在正确使用语法方面遇到困难。
I'd like to find all Children where the a child's grand_parent has a value equal to TRUE, but I'm having trouble getting the syntax right. Something like:
Child.where(grand_parent.value: TRUE)
推荐答案
您需要在两者之间加入模型才能引用 GrandParent
,因此您必须先加入父母
,然后再进行过滤。
You need to join the models in-between to be able to reference GrandParent
so you would have to join Parent
first and then filter.
Child.joins(parent:[:grand_parent])。where('grand_parents.value为TRUE')
不过只是验证一下评估 grand_parents
表上的实际列,还是只获取与<$ c相关联的所有孩子
$ c>祖父母?
Just to verify though, is value an actual column on the grand_parents
table or do you just want to get all the children
that have associated grand_parents
?
如果这样...
Child.joins(parent:[:grand_parent])
应该可以工作
如果您想让所有未关联 grand_parent
可以做的对象
if you want to get all the children without associated grand_parent
objects you can do
Child.joins(:parent).where('不存在(从grand_parents中选择1,其中grand_parents.id = Parents.grand_parent_id')
如果它们之间有一个连接表,例如 grand_parent_parents
表
it would be slightly different if there's a join table in between like a grand_parent_parents
table
Child.joins(:parent).where('不存在(从grand_parent_parents中选择1,其中grand_parent_parents.parent_id = parent.id')
这篇关于ActiveRecord:按祖父母值查找记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!