【问题标题】:mongoid 4 wrong number of arguments (3 for 1) for scopemongoid 4 范围的参数数量错误(3 代表 1)
【发布时间】: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


    【解决方案1】:

    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_idrecipient_id 组合成一个数组字段:

    field :involved_ids, :type => Array
    

    这样你就可以说:

    where(:involved_ids => user.id)
    

    并避免 OR 问题。当然,您仍然有单独的 sender_idrecipient_id 字段,您只需复制数据以更好地适应您的查询。对数据进行非规范化以适合您的查询在 MongoDB 中很常见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多