Han*_*les 9 postgresql activerecord ruby-on-rails ruby-on-rails-3
我有一个has_many
与另一个模型有关系的模型,如下所示:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
end
Run Code Online (Sandbox Code Playgroud)
由于有些父母可能没有孩子,我想做一个只返回有孩子的父母的查询.我怎么会这样做?
由于我在Rails 3上执行此操作,如果此查询不使用where.not.
语法将会有所帮助.
Aza*_*ine 14
Parent.includes(:child).where.not(children: {id: nil})
要么
Parent.joins(:child).where.not(children: {id: nil}).distinct
Parent.joins(:child).where('children.id NOT NULL').distinct
Mar*_*n13 12
Rails 7 引入了一种检查关联是否存在的新方法 - where.linked。
请看一下下面的代码片段:
# Before:
account.users.joins(:contact).where.not(contact_id: nil)
# After:
account.users.where.associated(:contact)
Run Code Online (Sandbox Code Playgroud)
这是在后台使用的 SQL 查询的示例:
Post.where.associated(:author)
# SELECT "posts".* FROM "posts"
# INNER JOIN "authors" ON "authors"."id" = "posts"."author_id"
# WHERE "authors"."id" IS NOT NULL
Run Code Online (Sandbox Code Playgroud)
因此,您的具体情况可以重写如下:
Parent.where.associated(:child)
Run Code Online (Sandbox Code Playgroud)
谢谢。
资料来源:
笔记:
归档时间: |
|
查看次数: |
3130 次 |
最近记录: |