Datamapper: report why I can't destroy record
Asked Answered
M

3

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?

Marino answered 9/1, 2013 at 10:45 Comment(1)
what about the sql logs?Defeat
B
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
Brazen answered 1/12, 2014 at 12:13 Comment(3)
Excellent work. Thanks! +1 @Ger -- Please accept this answer!Miles
Great work indeed and very helpful! Thanks a lot @Samuel Rizzo!Soil
This should be a built-in method in DM, nice one.Jonasjonathan
S
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。

Semi answered 26/11, 2013 at 13:4 Comment(0)
A
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
Asseverate answered 12/1, 2013 at 0:11 Comment(2)
That does not help. The errors don't contain anything helpful, and model.destroy returns false, it does not raise an exception.Karame
@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.Asseverate

© 2022 - 2024 — McMap. All rights reserved.