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
deleteanddestroy. In your controller you callwhich will just execute a SQL
DELETEbut will not call any callbacks. That’s why in normal cases you want to usedestroyinstead. 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.