:dependent => :destroy isn't calling the destroy method before the deletion?
I have a note model, with the following association
note.rb
has_many :note_categories, :dependent => :destroy
has_many :categories, :through => :note_categories
The NoteCategory model was created to function as a join table between notes and categories. Initially it was just a model/table, but I've created a controller to do some custom stuff when someone is removing a category from a note.
note_categories_controller.rb
def destroy
p "in notes_categories_controller destroy"
note_category_to_delete = NoteCategory.find(params[:id])
#some custom stuff
note_category_to_delete.destroy
respond_to do |format|
format.html { redirect_to(notes_url }
format.xml { head :ok }
end
end
This works fine, because I can use this link to create a button which will remove a category from a note:
<%= button_to 'Remove', note_category, :confirm => 'Are you sure?', :controller => :note_categories, :method => :delete %>
and it works fine.
The problem is, when I delete a note, the note_category rows the belonged to the note are getting deleted, but the destroy method isn't being run. I开发者_C百科 know this because the custom code isn't being run, and the terminal output in the first line doesn't show up in the terminal. Here is the terminal output:
Note Load (0.7ms) SELECT * FROM "notes" WHERE ("notes"."id" = 245)
NoteCategory Load (0.5ms) SELECT * FROM "note_categories" WHERE ("note_categories".note_id = 245)
NoteCategory Destroy (0.3ms) DELETE FROM "note_categories" WHERE "id" = 146
Note Destroy (0.2ms) DELETE FROM "notes" WHERE "id" = 245
I thought that by using :dependent => :destroy, the destroy method in the NoteCategories Controller should run before it's deleted. What am I doing wrong?
:dependent => :destroy
will call the destroy method on the model not the controller.
From the documentation:
If set to :destroy all the associated objects are destroyed alongside this object by calling their destroy method.
That is, if you want something custom to your note_categories before being destroyed, you'll have to either override the destroy
method in your NoteCategory model, or use an after_destroy/before_destroy callback.
Either way, using :dependent => :destroy
will never execute code contained within your controller, which is why you're not seeing the output of the puts
statement in the terminal.
精彩评论