Permalink
Browse files

support references_many_as_array eager loading

  • Loading branch information...
1 parent 943e985 commit 9d9b272030f3b3fc298e9ecea7a1918b7d05c7a6 @flyerhzm committed Oct 9, 2010
Showing with 29 additions and 0 deletions.
  1. +8 −0 lib/mongoid/criterion/eager_loading.rb
  2. +21 −0 spec/unit/mongoid/criterion/eager_loading_spec.rb
@@ -38,6 +38,14 @@ def preload(documents)
eager_association.send(reflection.foreign_key) == document.id
})
end
+ elsif reflection.association == Mongoid::Associations::ReferencesManyAsArray
+ ids = documents.collect(&:"#{reflection.foreign_key}").flatten
+ eager_associations = reflection.name.singularize.camelize.constantize.find(ids).to_a
+ documents.each do |document|
+ document.send("#{reflection.name}=", eager_associations.find_all { |eager_association|
+ eager_association.id == document.send(reflection.foreign_key)
+ })
+ end
elsif reflection.association == Mongoid::Associations::ReferencedIn
ids = documents.collect(&:"#{reflection.foreign_key}")
eager_associations = reflection.name.singularize.camelize.constantize.find(ids).to_a
@@ -28,6 +28,11 @@
person1.posts.create(:title => "post2")
person2.posts.create(:title => "post3")
person2.posts.create(:title => "post4")
+
+ person1.preferences.create(:name => "preference1")
+ person1.preferences.create(:name => "preference2")
+ person2.preferences.create(:name => "preference3")
+ person2.preferences.create(:name => "preference4")
end
it "preload references_one association" do
@@ -50,6 +55,14 @@
criteria.preload([person1, person2])
end
+ it "preload references_many association" do
+ Preference.expects(:find).with((person1.preferences + person2.preferences).collect(&:id)).returns(person1.preferences + person2.preferences)
+
+ criteria = Mongoid::Criteria.new(Person)
+ criteria.includes(:preferences)
+ criteria.preload([person1, person2])
+ end
+
it "preload referenced_in association" do
Person.expects(:find).with([person1.id, person2.id]).returns([person1, person2])
@@ -77,6 +90,14 @@
reflection.name.should == "posts"
end
+ it "with references_many_as_array" do
+ criteria = Mongoid::Criteria.new(Person)
+ reflection = criteria.association_reflection(Person, :preferences)
+ reflection.association.should == Mongoid::Associations::ReferencesManyAsArray
+ reflection.foreign_key.should == "preference_ids"
+ reflection.name.should == "preferences"
+ end
+
it "with referenced_in" do
criteria = Mongoid::Criteria.new(Game)
reflection = criteria.association_reflection(Game, :person)

0 comments on commit 9d9b272

Please sign in to comment.