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.
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.
Ensure that you are calling Slider#destroy
in order to trigger callbacks. Slider#delete
will simply delete the record without calling them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With