【发布时间】:2015-06-12 07:44:53
【问题描述】:
我试图创建以下范围:
scope :involving, -> (user) do
where("conversations.sender_id =? OR conversations.recipient_id =?", user.id, user.id)
end
但我明白了:
参数数量错误(3 比 1)
我做错了什么。
提前致谢。
【问题讨论】:
标签: ruby-on-rails mongoid
我试图创建以下范围:
scope :involving, -> (user) do
where("conversations.sender_id =? OR conversations.recipient_id =?", user.id, user.id)
end
但我明白了:
参数数量错误(3 比 1)
我做错了什么。
提前致谢。
【问题讨论】:
标签: ruby-on-rails mongoid
Mongoid 的where 不像a = ? OR b = ? 那样理解SQL sn-ps,它只需要一个哈希参数。因此您的“3 for 1”错误。
您想使用any_of 构建:$or 查询:
any_of(
{ :sender_id => user.id },
{ :recipient_id => user.id }
)
请注意多个any_ofs 组合在一起,因此:
M.any_of(a, b).any_of(c, d)
在说:
a OR b OR c OR d # any_of(a, b, c, d)
而不是
(a OR b) AND (c OR d)
如你所料。
如果您希望每个组合 OR 条件,那么您可能希望将 sender_id 和 recipient_id 组合成一个数组字段:
field :involved_ids, :type => Array
这样你就可以说:
where(:involved_ids => user.id)
并避免 OR 问题。当然,您仍然有单独的 sender_id 和 recipient_id 字段,您只需复制数据以更好地适应您的查询。对数据进行非规范化以适合您的查询在 MongoDB 中很常见。
【讨论】: