mongoid 4 范围的参数数量错误(3 为 1)
mongoid 4 wrong number of arguments (3 for 1) for scope
我正在尝试创建以下范围:
scope :involving, -> (user) do
where("conversations.sender_id =? OR conversations.recipient_id =?", user.id, user.id)
end
但我得到:
wrong number of arguments (3 for 1)
我做错了什么。
提前致谢。
Mongoid 的 where
不理解像 a = ? OR b = ?
这样的 SQL 片段,它只需要一个散列参数。因此你的“3 for 1”错误。
您想使用 any_of
构建一个 :$or
查询:
any_of(
{ :sender_id => user.id },
{ :recipient_id => user.id }
)
注意多个 any_of
组合在一起,因此:
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.
对数据进行非规范化以适合您的查询很常见
我正在尝试创建以下范围:
scope :involving, -> (user) do
where("conversations.sender_id =? OR conversations.recipient_id =?", user.id, user.id)
end
但我得到:
wrong number of arguments (3 for 1)
我做错了什么。
提前致谢。
Mongoid 的 where
不理解像 a = ? OR b = ?
这样的 SQL 片段,它只需要一个散列参数。因此你的“3 for 1”错误。
您想使用 any_of
构建一个 :$or
查询:
any_of(
{ :sender_id => user.id },
{ :recipient_id => user.id }
)
注意多个 any_of
组合在一起,因此:
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.