Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Treebook - Remove pictures when album is deleted

Hello,

I've got an app that used the basics from the treebook application.

When I show a picture I've been generating a random image at the side that the user might also be interested in which the user can click through to.

The problem is that the images are sometimes showing images that have already been deleted.

I think if someone deletes an individual image then it disappears. But if the album is deleted, the images are still in the system and still show up in my random images despite there being no way to access them.

How do I need to adjust the destroy method for the album to make sure that all the pictures are removed and not just access to the album? Or is there a better way to do this?

2 Answers

In the album model, you probably have:

class Album 
    has_many :pictures
end

What you need is to tell rails that when you delete an album, to destroy all pictures associated to that album. It is a simple line:

class Album 
    has_many :pictures, dependent: :destroy
end

This will trigger callbacks to automatically delete the pictures when the album is deleted.

Thank you. Worked perfectly.