Using Datamapper, I have a model Album that has n, :photos which has a Paperclip::Resource
With ActiveRecord I would just have had:
has_many :photos, dependent: :destroy
in my Album model, in order to delete the photos at the same time as the Album, but with Datamapper it seems you have to roll your own. In Sinatra, to delete the album I have:
delete '/albums/:id' do
a = Album.get params[:id]
a.destroy
redirect '/'
end
and a before filter in the Album model:
before :destroy do
photos.destroy
end
but the before filter is never called.
If I put use the bang method, a.destroy!, the album is destroyed but not the Photos.
No errors are produced and no Exceptions raised.
UPDATE
There are errors, but with an empty errors hash:
INFO -- : #<DataMapper::Validations::ValidationErrors:0x13740dc @resource=#<Album @id=2 @name="Quaver" @created_at=#<DateTime: 2013-02-07T10:30:36+00:00 (5895194251/2400,0/1,2299161)> @updated_at=#<DateTime: 2013-02-07T10:30:36+00:00 (5895194251/2400,0/1,2299161)>>, @errors={}>
So clearly I have validation issues. However I have not set any validations in my Models:
class Photo
include DataMapper::Resource
include Paperclip::Resource
property :id, Serial
property :title, String
property :created_at, DateTime
property :updated_at, DateTime
has_attached_file :data, url: "/:attachment/:id/:style/:basename.:extension",
path: "# {APP_ROOT}/public/:attachment/:id/:style/:basename.:extension"
belongs_to :album
end
class Album
include DataMapper::Resource
property :id, Serial
property :name, String
property :created_at, DateTime
property :updated_at, DateTime
has n, :photos
before :destroy do
photos.destroy
end
end
So the before filter is not being called because of the ValidationErrors, but where do they come from when they are not explicitly set?
Any help, gratefully received. Thanks.
Apparently when you use:
you are implicitly using dm-constraints, which protects dependent models by default. Simply giving permission to destroy (much like ActiveRecord) does the trick:
Damn that hurt!