Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

before_destroy and dependent destroy not firing

I have the following model associations:

class Slider < ActiveRecord::Base
  has_one :featured_happening, :as => :featured_item, :dependent => :destroy   
  before_destroy :destroy_featured_happening
  after_create :create_featured_happening
end

class FeaturedHappening < ActiveRecord::Base
  belongs_to :featured_item, :polymorphic => true
end

When I destroy a Slider object I thought the dependent => :destroy would automatically destroy the featured_item but it does not.

Slider controller

 def destroy    
    slider = Slider.find(params[:id])
    slider.delete
    render(:status => :ok, :nothing => true )
  end

So then I tried a callback with before_destroy to manually delete the featured_item when a slider object is destroyed and nothing is getting called.

How can I get the featured_item to be deleted when I delete a slider object? Using Rails 3.2.

like image 234
chell Avatar asked Mar 26 '12 03:03

chell


2 Answers

You just observed the difference between delete and destroy. In your controller you call

slider.delete

which will just execute a SQL DELETE but will not call any callbacks. That's why in normal cases you want to use destroy instead. It will fetch the object (if necessary), call the callbacks including recursive destroys and only then deletes the object from the database.

See the documentation for delete and destroy for more information.

like image 85
Holger Just Avatar answered Oct 15 '22 00:10

Holger Just


Ensure that you are calling Slider#destroy in order to trigger callbacks. Slider#delete will simply delete the record without calling them.

like image 26
jamie_gaskins Avatar answered Oct 15 '22 00:10

jamie_gaskins