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 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? Thanks for reading.