Search code examples
rubyassociationsdatamapperruby-datamapper

DataMapper one-to-many delete failing


class Alpha
  include DataMapper::Resource
  property :id,   Serial
  property :name, String
  has n, :betas
end

class Beta
  include DataMapper::Resource
  property :id,   Serial
  property :name, String
  belongs_to :alpha
end

# Create an Alpha with two Betas
@alpha = Alpha.new(:name => 'A')
@alpha.betas << Beta.new(:name => 'B')
@alpha.betas << Beta.new(:name => 'C')
@alpha.save

puts @alpha.betas.inspect
puts "Destroyed? #{@alpha.betas.first.destroy}"
puts @alpha.betas.inspect

For some reason, DataMapper isn't deleting the associated Beta object.

Is this a bug or am I missing something?

A complete example is in this gist https://gist.github.com/2219479

EDIT:

The answer is to reload the Alpha object after destroying the Beta

puts @alpha.betas.inspect
puts "Destroyed? #{@alpha.betas.first.destroy}"
puts @alpha.betas.reload
puts @alpha.betas.inspect

Solution

  • Copying the answer from the edited question body in order to remove this question from the "Unanswered" filter:

    The answer is to reload the Alpha object after destroying the Beta

    puts @alpha.betas.inspect
    puts "Destroyed? #{@alpha.betas.first.destroy}"
    puts @alpha.betas.reload
    puts @alpha.betas.inspect
    

    ~ answer per Craig552uk