mongoid 4 wrong number of arguments (3 for 1) for scope

144 views Asked by At

I trying to create the following scope:

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

but I get:

wrong number of arguments (3 for 1)

What I'm doing wrong.

Thanks in advance.

1

There are 1 answers

0
mu is too short On BEST ANSWER

Mongoid's where doesn't understand SQL snippets like a = ? OR b = ?, it only wants a single hash argument. Hence your "3 for 1" error.

You want to use any_of to build an :$or query:

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

Beware that multiple any_ofs are combined so this:

M.any_of(a, b).any_of(c, d)

is saying:

a OR b OR c OR d # any_of(a, b, c, d)

rather than

(a OR b) AND (c OR d)

as you might expect.

If you're expecting to every combine OR conditions then you might want to combine the sender_id and recipient_id into a single array field:

field :involved_ids, :type => Array

so that you could say:

where(:involved_ids => user.id)

and avoid the OR-problem. You'd still have separate sender_id and recipient_id fields of course, you'd just duplicate the data to better fit your queries. Denormalizing your data to suit your queries is quite common with MongoDB.