2015-06-12 45 views
0

我試圖創建以下範圍:mongoid 4錯誤的參數數目(3 1)範圍

scope :involving, -> (user) do 
    where("conversations.sender_id =? OR conversations.recipient_id =?", user.id, user.id) 
    end 

,但我得到:

錯誤的參數數目(3 1)

我做錯了什麼。

在此先感謝。

回答

0

Mongoid的where不理解像a = ? OR b = ?這樣的SQL片段,它只需要一個散列參數。因此你的「3對1」的錯誤。

你想用any_of建立一個:$or查詢:

any_of(
    { :sender_id => user.id }, 
    { :recipient_id => user.id } 
) 

當心多個any_of s的組合,以這樣的:

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) 

正如您所料。

如果你希望每一個組合或條件,那麼你可能要到sender_idrecipient_id結合成一個單一陣列場:

field :involved_ids, :type => Array 

,這樣你可以說:

where(:involved_ids => user.id) 

並避免OR問題。當然,您仍然有單獨的sender_idrecipient_id字段,您只需複製數據以更好地適合您的查詢。非規範化數據以適合您的查詢在MongoDB中非常常見。

相關問題