From 0d268905e7c1cd8f4e872dd829f7e97f3172eb33 Mon Sep 17 00:00:00 2001 From: maxwell Date: Wed, 21 Jul 2010 17:05:21 -0700 Subject: [PATCH] DG MS all photos of a album are destroyed on album deletion --- app/models/album.rb | 8 ++++++++ spec/models/album_spec.rb | 18 +++++++++++++++--- spec/models/photo_spec.rb | 4 +++- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/app/models/album.rb b/app/models/album.rb index 914da9837..7d791c4c8 100644 --- a/app/models/album.rb +++ b/app/models/album.rb @@ -10,6 +10,8 @@ class Album validates_presence_of :name + before_destroy :destroy_photos + def prev_photo(photo) n_photo = self.photos.where(:created_at.lt => photo.created_at).sort(:created_at.desc).first n_photo ? n_photo : self.photos.sort(:created_at.desc).first @@ -20,4 +22,10 @@ class Album p_photo ? p_photo : self.photos.sort(:created_at.desc).last end + protected + + def destroy_photos + photos.each{|p| p.destroy} + end + end diff --git a/spec/models/album_spec.rb b/spec/models/album_spec.rb index cb5ac690f..def77bacf 100644 --- a/spec/models/album_spec.rb +++ b/spec/models/album_spec.rb @@ -30,12 +30,24 @@ describe Album do album.photos.count.should == 1 end + it 'should remove all photos on album delete' do + photo_one = Photo.create(:person => @user, :album => @album, :created_at => Time.now) + photo_two = Photo.create(:person => @user, :album => @album, :created_at => Time.now-1) + photo_three = Photo.create(:person => @user, :album => @album, :created_at => Time.now-2) + + @album.photos += [photo_one, photo_two, photo_three] + + Photo.all.count.should == 3 + @album.destroy + Photo.all.count.should == 0 + end + describe 'traversing' do before do @album = Album.create(:name => "test collection") - @photo_one = Photo.create(:person => @user, :created_at => Time.now) - @photo_two = Photo.create(:person => @user, :created_at => Time.now-1) - @photo_three = Photo.create(:person => @user, :created_at => Time.now-2) + @photo_one = Photo.create(:person => @user, :album => @album, :created_at => Time.now) + @photo_two = Photo.create(:person => @user, :album => @album, :created_at => Time.now+1) + @photo_three = Photo.create(:person => @user, :album => @album, :created_at => Time.now+2) @album.photos += [@photo_one, @photo_two, @photo_three] end diff --git a/spec/models/photo_spec.rb b/spec/models/photo_spec.rb index c5ab80c75..4baf36a2a 100644 --- a/spec/models/photo_spec.rb +++ b/spec/models/photo_spec.rb @@ -34,8 +34,10 @@ describe Photo do it 'must have an album' do - photo = Photo.create(:person => @user) + photo = Photo.new(:person => @user) photo.valid?.should be false + photo.album = Album.new(:name => "foo") + photo.save Photo.first.album.name.should == 'foo' end end