I need to select transactions with the same type as a given transaction. And I need to check that it doesn’t return all transactions with the nil type.
With ActiveRecord I can easily write:
given_transaction = Transaction.first
needed_transactions = Transaction.where('type != nil and type = ?', given_transaction.type)
and all works
when I try to write the same thing with mongoid:
needed_transactions = Transaction.where(:type => given_transaction.type, :type.ne => nil)
It generates the following query:
"query"=>{:type=>{"$ne"=>"planned"}}
In other words, mongoid ignores the first check and only uses the last check on the field.
I tried “all_of”, “all_in”, “and” — and still can’t find the working solution.
Maybe I am doing something wrong… My world is going upside down because of this… :(((
From the fine manual:
And looking at the Criteria docs for
wherewe see a bunch of examples with a single condition. But remember the chainability mentioned above. Perhaps you’re looking for this:The
Criteria#anddocs might make good reading as well:I have to admit that I don’t understand why you’re checking
:typetwice like that though; ifgiven_transaction.type.nil?is possible then you could deal with that without even querying your database.And BTW, with ActiveRecord you’d want to say this:
As far as the strange query you’re getting is concerned, when you do this:
Mongoid ends up trying to build a Hash with two values for the
:typekey:and somehow it ends up replacing the
nilwith'planned'. I don’t know the internal details of Mongoid’swhereor the methods it patches into Symbol, I’m just backtracking from the observed behavior.