我有用户模型,我需要创建一个查询,像这样
SELECT DISTINCT u.id FROM users as u
LEFT JOIN lists_users as lu ON lu.user_id = u.id
WHERE u.id != 3
AND lu.list_id != 34
我试试
scope :include_current_user, lambda { |user, list|
joins('LEFT JOIN lists_users AS lu ON lu.user_id = id')
.where('id != :user_id AND lu.list_id != :list_id', user_id: user.id, list_id: list.id)
}
但我有错误
SQLite3::SQLException: ambiguous column name: id: SELECT "users".* FROM "users" LEFT JOIN lists_users AS lu ON lu.user_id = id WHERE (id != 2 AND lu.list_id != 34)
如何借助ActiveRecord查询创建它?
答案 0 :(得分:2)
如果您使用的是Rails 5,则可以使用left_outer_joins
进行查询,也可以使用not
来否定条件的位置,同时也可以防止出现条件不明确的条件表名,所以你将完成像
left_outer_joins(:list_users).where.not(users: { id: user.id }, list_users: { list_id: list.id })