Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datamapper: report why I can't destroy record

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?

like image 534
Gerard Avatar asked Jan 09 '13 10:01

Gerard


2 Answers

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
like image 187
Samuel Rizzo Avatar answered Nov 09 '22 10:11

Samuel Rizzo


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。

like image 30
xianlinbox Avatar answered Nov 09 '22 11:11

xianlinbox