我有两张桌子users
& contacts
用户
| id | name | last_name |
|:-----------|------------:|:------------:|
| 1 | John | Abraham
| 2 | Tom | column
| 3 | Bob | Warner
| 4 | Smith | Warne
| 5 | Brad | Pitt
联系人
| id | user_id | contact |active | category_id |
|:-----------|-----------:|:-------------:|:---------:|:------------:|
| 1 | 1 | 132423 | false | 2
| 2 | 1 | 131423 | true | 3
| 3 | 1 | 142423 | true | 1
| 4 | 2 | 132413 | true | 1
| 5 | 2 | 132425 | false | 2
| 6 | 2 | 131420 | true | 3
| 7 | 3 | 131323 | true | 3
| 8 | 3 | 332423 | true | 1
| 9 | 3 | 232423 | false | 2
| 10 | 4 | 132523 | false | 1
我希望第1类没有有效(false)
的用户或没有该类别联系人的用户以及以下联系人
| id | name | last_name |
|:-----------|------------:|:------------:|
| 4 | Smith | Warne
| 5 | Brad | Pitt
我尝试了类似的内容,但它没有工作
User.includes(:contacts).where(contacts: {user_id: nil, category_id: 1 })
我可以使用两个不同的查询来完成,但没有得到如何在单个查询中编写它
u_ids = Conatct.where(category_id: 1, active: true).pluck(:user_id)
users = User.where.not(id: u_ids)
答案 0 :(得分:0)
AVAudioFile
eager_load在'contacts'表上执行左外连接。对于与联系人表无关联的所有用户 - 对于此查询,contacts.id将最终为零