I’ve two models: Event and Link.
- Event
has_many :links - Link
belongs_to :event
I would like to delete all the related links when the events_controller.rb#destroy action is invoked.
This is the destroy action:
def destroy
@event = Event.find(params[:id])
@event.destroy
links = @event.links
for link in links do
link.destroy
end
respond_to do |format|
format.html { redirect_to :back }
format.json { head :no_content }
end
end
But it doesn’t seem to be working. Where am I going wrong?
Stop right there, you don’t have to reinvent this wheel. Rails does this for you.
In your models, simply specify
And when you delete an
Event, all its links will be automatically destroyed.From the Rails Guide on Deleting From Associations: