1

I have a existing rails query but it doesn't work with mongoid .I need to convert so that it works with mongoid

Here is the query

scope :between, -> (sender_id,recipient_id) do
    where("(conversations.sender_id = ? AND conversations.recipient_id =?) OR (conversations.sender_id = ? AND conversations.recipient_id =?)", sender_id,recipient_id, recipient_id, sender_id)
 end

I am new to mongoid I tried but was not able to find suitable solution

Mongoid 3.4.2
Rails 5.0.1
ruby '2.3.0'
user6551529
  • 121
  • 14

1 Answers1

2

Assuming the declaration is in the Conversation model:

scope :between, -> (sender_id,recipient_id) do
    any_of({sender_id: sender_id, recipient_id: recipient_id}, {sender_id: recipient_id, recipient_id: sender_id})
end

Update:

Another solution using in operator, will cover your query as well but will include unwanted cases of sender_id: sender_id, recipient_id: recipient_id.

scope :between, -> (sender_id, recipient_id) do
    args = [sender_id, recipient_id]
    where(:sender_id.in => args , :recipient_id.in => args)
end

I will prefer the first option, but the second one could do the trick as well if you sure that your pair values are unique for each model.

vvahans
  • 1,849
  • 21
  • 29