Skip to content

Commit

Permalink
Merge pull request mongomapper#462 from jnunemaker/association-each-n…
Browse files Browse the repository at this point in the history
…ot-yielding

Provide a fix for many associations not yielding to each in callbacks.
  • Loading branch information
greatuserongithub committed Oct 3, 2012
2 parents e3521dc + 9844b2a commit d1eb6bc
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
29 changes: 29 additions & 0 deletions test/functional/associations/test_many_documents_proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down

0 comments on commit d1eb6bc

Please sign in to comment.