I was doing the following to remove associated records from comments when removing the parent event record:
@event = Event.find(params[:id]) @comments = @event.comments.find(:all) if @event.destroy && Comment.destroy(@comments) flash[:notice] = "Event deleted" else flash[:error] = "There was a problem deleting the event" end redirect_to :action => 'index'
This worked fine, but changing the event model to:
has_many :comments, :dependent => :destroy
… means I can change the controller code to:
@event = Event.find(params[:id]) if @event.destroy flash[:notice] = "Event deleted" else flash[:error] = "There was a problem deleting the event" end redirect_to :action => 'index'
On a side note, you have to do Comment.destroy(@comments) since this doesn’t work:
>> @event = Event.find(1)
=> #<event id: 1, name: "Fabric", location_id: 1, lineup: "Mark Farina<br />Terry Francis<br />Jon Marsh<br />James ...", date: "2005-04-23", url: "www.fabriclondon.com", tickets: "", price: "£15/£12 NUS", time: "N/A", user_id: 1>
>> @comments = @event.comments.find(:all)
=> []
>> @comments.destroy
NoMethodError: undefined method `destroy' for []:Array
from (irb):3
>> Comment.destroy(@comments)
=> []
>>