5

I'm setting up my db model using datamapper and dm-contraints. I have two models which have a many to many relationship but when I try to destroy one, the only message I get is false.

Is it possible to get datamapper to give me more feedback one which relationship is exactly causing the problem?

Gerard
  • 4,688
  • 5
  • 48
  • 76

3 Answers3

10

With datamapper 1.2.1:

def why_you_no_destroy? model
  preventing = []
  model.send(:relationships).each do |relationship|
    next unless relationship.respond_to?(:enforce_destroy_constraint)
    preventing << relationship.name unless relationship.enforce_destroy_constraint(model)
  end
  preventing
end
Samuel Rizzo
  • 2,061
  • 2
  • 14
  • 18
2

Unfortunately DM doesn't provide a way to report why destroy failed.

Most of time the destroy failed because of its associations. DM have a mechanism to avoid orphan records.

To avoid this kind of destroy failed, you can Use dm-constraints(https://github.com/datamapper/dm-constraints ) to set up true database level foreign key references, which default to protect, but can be set to cascade deletes instead.

class List
  has n, :todos, :constraint => :destroy (or :destroy!)
end

Sadly, Currently dm-constraints only supports PostgreSQL and MySQL.

For other database, you can check all the associations manually and delete them first, then delete the model。

xianlinbox
  • 879
  • 10
  • 9
0

You can get information on DataMapper errors from

model.destroy
if model
  model.errors.each do |error|
    p error
  end
end

Sometimes that doesn't tell you anything though, in which case you can put your code inside of a begin/rescue block e.g.

begin
  model.destroy
rescue Exception => exc
  p exc
end
AlexQueue
  • 5,549
  • 4
  • 26
  • 41
  • That does not help. The errors don't contain anything helpful, and model.destroy returns false, it does not raise an exception. – foxdonut Jan 29 '13 at 19:56
  • @FredericDaoud Sorry, this was how I solved the same issue when it happened to me (by telling me I had an associated object that wasn't being destroyed). Double-check to make sure all your associations are paired correctly and that they are destroyed properly. – AlexQueue Jan 29 '13 at 21:16