Skip to content

Instantly share code, notes, and snippets.

@kasima
Created May 5, 2011 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kasima/957582 to your computer and use it in GitHub Desktop.
Save kasima/957582 to your computer and use it in GitHub Desktop.
Mongoid $or bug
class Parent
include Mongoid::Document
field :pants
field :shirts
embeds_many :children
end
class Child
include Mongoid::Document
field :pants
field :shirt
embedded_in :parent
end
not_matching_child_1 = Child.new(:pants => 'red', :shirt => 'white')
not_matching_child_2 = Child.new(:pants => 'white', :shirt => 'red')
matching_child = Child.new(:pants => 'red', :shirt => 'red')
parent_with_children = Parent.create(:children => [not_matching_child_1, not_matching_child_2, matching_child])
not_matching_parent_1 = Parent.create(:pants => 'red', :shirt => 'white')
not_matching_parent_2 = Parent.create(:pants => 'white', :shirt => 'red')
matching_parent = Parent.create(:pants => 'red', :shirt => 'red')
# find non matching parents
Parent.where("$or" => [{:pants => 'red', :shirt => 'white'}, {:pants => 'white', :shirt => 'red'}]).count
# => 2
# find non matching children
parent_with_children.children.where("$or" => [{:pants => 'red', :shirt => 'white'}, {:pants => 'white', :shirt => 'red'}]).count
# => 3
# But should return 2!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment