Rails 包含条件 [英] Rails includes with conditions
问题描述
Rails > 3.2 是否可以在includes
方法生成的join 语句中添加条件?
Is is possible in Rails > 3.2 to add conditions to the join statement generated by the includes
method?
假设我有两个模型,Person 和 Note.每个人有许多笔记,每个笔记属于一个人.每个笔记都有一个属性important
.
Let's say I have two models, Person and Note. Each person has many notes and each note belong to one person. Each note has an attribute important
.
我想找到所有的人只预加载重要的笔记.在 SQL 中,这将是:
I want to find all the people preloading only the notes that are important. In SQL that will be:
SELECT *
FROM people
LEFT JOIN notes ON notes.person_id = people.id AND notes.important = 't'
在 Rails 中,唯一类似的方法是使用 includes
(注意:joins
不会预加载注释),如下所示:
In Rails, the only similar way to do that is using includes
(note: joins
won't preload notes) like this:
Person.includes(:notes).where(:important, true)
但是,这将生成以下返回不同结果集的 SQL 查询:
However, that will generate the following SQL query which returns a different result set:
SELECT *
FROM people
LEFT JOIN notes ON notes.person_id = people.id
WHERE notes.important = 't'
请注意,第一个结果集包含所有人,第二个结果集仅包含与重要笔记相关联的人.
Please, notice that the first resultset includes all the people and the second one only the people associated to important notes.
另请注意 :conditions 自 3.1 起已弃用.
Also notice that :conditions are deprecated since 3.1.
推荐答案
Rails 5+ 语法:
Rails 5+ syntax:
Person.includes(:notes).where(notes: {important: true})
嵌套:
Person.includes(notes: [:grades]).where(notes: {important: true, grades: {important: true})
这篇关于Rails 包含条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!