我有一个 Event
模型,具有 user_id
在里面。我想选择这个模型的所有对象,指定 user_id
但不包括具体事件。所以我可以用这样的查询来做到这一点:
Event.where(user_id: user.id).where.not(id: id)
但是我可以将这两个结合起来吗
where
功能合二为一?我知道,例如,如果我需要查找具有指定
id
的事件s 和 user_id
s,我可以这样做:Event.where(user_id: user_id).where(id: id)
我可以用一个
where
压缩它调用而不是两个:Event.where(user_id: user_id, id: id)
但是如果我使用
where
,我可以做同样的事情吗?和 where.not
?
最佳答案
您可以按照以下方式编写以添加 where 和 where.not :
Event.where(
"user_id = ? AND id != ?",
user.id,
id
)
所以如果 user_id = 1 和 id = 2
这将返回带有 user_id 1 而没有 id 2 的记录:)
关于sql - 有没有办法在 Rails 中将 where 和 where.not 组合成一个条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38894071/