如何优化 Activerecord 中的 select 查询?
How do I optimize a select query in Activerecord?
我正在寻找是否有更好的方法来编写以下 ActiveRecord 查询。
@posts = Post.select {|x| x.section.nil?}
我对这个查询所做的是搜索帖子,只选择不再有相关部分并被孤立的帖子。
有更好的方法吗?我正在使用 rails 3.2.
非常感谢。
这应该有效:
Post.joins('left outer join sections on sections.id = posts.section_id').where('sections.id is null and posts.section_id is not null')
或者更短的方式,使用 eager_load
:
Post.eager_load(:section).where('sections.id is null and posts.section_id is not null')
我正在寻找是否有更好的方法来编写以下 ActiveRecord 查询。
@posts = Post.select {|x| x.section.nil?}
我对这个查询所做的是搜索帖子,只选择不再有相关部分并被孤立的帖子。
有更好的方法吗?我正在使用 rails 3.2.
非常感谢。
这应该有效:
Post.joins('left outer join sections on sections.id = posts.section_id').where('sections.id is null and posts.section_id is not null')
或者更短的方式,使用 eager_load
:
Post.eager_load(:section).where('sections.id is null and posts.section_id is not null')