Rails ActiveRecord查询模糊列名称错误

时间:2016-11-29 20:51:46

标签: ruby-on-rails activerecord

我有用户模型,我需要创建一个查询,像这样

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查询创建它?

1 个答案:

答案 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 })