0

Model.excludes(state: "this).excludes(state: "that")

produces:

"state"=>{"$ne"=>"that"}

but what I really want is to exclude all records that have either "this" or "that"

  • Possible duplicate : http://stackoverflow.com/questions/9035031/how-do-i-get-the-negation-of-a-mongoid-query – Raindal Dec 31 '12 at 00:55
  • not really, they're excluding on 2 *different* attributes. I want to exclude on the SAME attribute, just with 2 different values. Thank you though for the comment, it has at least given me something else to play with. – user1935272 Dec 31 '12 at 03:07
  • Did you try something like : `Model.excludes(state: "this", state: "that")` ? – Raindal Dec 31 '12 at 04:20
  • Yes. No dice. The second one overrides the first. (If the two attributes are different (:state and :something_else), Mongoid constructs the query properly, but not when it's the same attribute). – user1935272 Dec 31 '12 at 04:57
  • That one should help : http://stackoverflow.com/questions/7598450/how-to-make-a-query-with-or-condition-in-mongoid – Raindal Dec 31 '12 at 05:07

1 Answers1

1

Here's a working test that uses Model.not_in

http://two.mongoid.org/docs/querying/criteria.html#not_in

app/models/model.rb

class Model
  include Mongoid::Document
  field :state, type: String
end

test/unit/model_test.rb:

require 'test_helper'

class ModelTest < ActiveSupport::TestCase
  def setup
    Model.delete_all
  end

  test "not_in" do
    Model.create({ state: 'this' })
    Model.create({ state: 'that' })
    Model.create({ state: 'not this or that'})
    assert_equal(3, Model.count)
    p Model.not_in(state: ['this', 'that']).to_a
    assert_equal(1, Model.not_in(state: ['this', 'that']).to_a.count)
  end
end

rake test:

Run options:

# Running tests:

[#<Model _id: 50e6fdef29daeb27e5000003, _type: nil, state: "not this or that">]
.

Finished tests in 0.021175s, 47.2255 tests/s, 94.4510 assertions/s.

1 tests, 2 assertions, 0 failures, 0 errors, 0 skips
Gary Murakami
  • 3,392
  • 1
  • 16
  • 20