Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #462 from jnunemaker/association-each-not-yielding

Provide a fix for many associations not yielding to each in callbacks.
  • Loading branch information...
commit d1eb6bcf129ae89c38e8835728ef9d38ad3bb37b 2 parents e3521dc + 9844b2a
@jnunemaker jnunemaker authored
View
6 lib/mongo_mapper/plugins/associations/many_documents_proxy.rb
@@ -5,7 +5,7 @@ module Associations
class ManyDocumentsProxy < Collection
include DynamicQuerying::ClassMethods
- def_delegators :query, *(Querying::Methods - [:to_a, :size, :empty?])
+ def_delegators :query, *(Querying::Methods - [:each, :to_a, :size, :empty?])
def replace(docs)
load_target
@@ -71,6 +71,10 @@ def save_to_collection(options={})
@target.each { |doc| doc.save(options) } if @target
end
+ def each(&block)
+ load_target.each(&block)
+ end
+
protected
def query(options={})
klass.
View
29 test/functional/associations/test_many_documents_proxy.rb
@@ -35,6 +35,35 @@ def pets
instance.pets.should_not be_empty
end
+ should "be able to iterate associated documents in a callback" do
+ @owner_class.class_eval do
+ before_save :search_pets
+
+ def search_pets
+ pets.each { |p| p.name = "Animal" }
+ end
+ end
+
+ owner = @owner_class.new
+ sophie = owner.pets.build(:name => "Sophie")
+ pippa = owner.pets.build(:name => "Pippa")
+
+ owner.save
+ owner.reload
+ owner.pets.reload
+
+ pets = []
+ owner.pets.each { |p| pets << p }
+
+ assert_equal(2, pets.size)
+ assert(pets.include?(sophie))
+ assert(pets.include?(pippa))
+
+ # Weird way of testing that the callback actually interated
+ assert_equal("Animal", sophie.reload.name)
+ assert_equal("Animal", pippa.reload.name)
+ end
+
should "allow assignment of many associated documents using a hash" do
person_attributes = {
'name' => 'Mr. Pet Lover',
Please sign in to comment.
Something went wrong with that request. Please try again.