Rails-仅查找存在has_many相关记录的记录 [英] Rails - only find records where has_many associated records are present
本文介绍了Rails-仅查找存在has_many相关记录的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个与其他模型具有 has_many
关系的模型,
I have a model with a has_many
relation with another model like so:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
end
由于有些父母可能没有孩子,所以我想执行一个查询,该查询仅返回确实有孩子的父母.我将如何处理这样的事情?
Since there are some parents that may not have children, I'd like to do a query that returns only the parents that DO have children. How would I go about something like this?
由于我是在Rails 3上执行此操作的,因此如果此查询不使用 where.not.
语法,将会很有帮助.
Since I'm doing this on Rails 3, it would be helpful if this query were to not use the where.not.
syntax.
推荐答案
路轨4
Parent.includes(:child).where.not(children:{id:nil})
或
Parent.joins(:child).distinct
Parent.joins(:child).distinct
这篇关于Rails-仅查找存在has_many相关记录的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文