如何在Rails Active Record查询中使用联接获取第二个表的结果

3

我的ActiveRecord查询是Note.joins(:user).where(category: "Actions"),生成的SQL如下:SELECT notes.* FROM notes INNER JOIN users ON users.id = notes.user_id WHERE notes.category = 'Actions'

我想要从用户表获取数据而不是笔记表,也就是说,我想要生成如下SQL:SELECT users.* FROM users INNER JOIN notes ON users.id = notes.user_id WHERE notes.category = 'Actions';

那么对应的Active Record查询语句应该是什么呢?

如果我写User.joins(:notes).where(category: "Actions"),则会抛出错误Mysql2::Error: Unknown column 'users.category',因为category属性属于notes表而不是users表。

1个回答

7
尝试这个 -
User.joins(:notes).where(notes: {category: "Actions"})

你能告诉我如何在AR的.where方法中传递条件运算符吗? 例如:Note.where(notes: {feeling_score: 7})将始终返回SELECT notes.* FROM notes WHERE notes.feeling_score = 7。我该如何在where子句中传递条件运算符,如<<= - Bloomberg
2
User.joins(:notes).where("notes.feeling_score < ? ", 7 ) @ArvindMehra - dp7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接