:dependent =>:destroy是不是在删除之前调用destroy方法?

我有一个笔记模型,具有以下关联

note.rb

has_many :note_categories, :dependent => :destroy has_many :categories, :through => :note_categories 

创建NoteCategory模型以用作注释和类别之间的连接表。 最初它只是一个模型/表,但我创建了一个控制器,当有人从一个笔记中删除一个类别时,做一些自定义的东西。

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 

这很好用,因为我可以使用此链接创建一个按钮,该按钮将从注释中删除一个类别:

  'Are you sure?', :controller => :note_categories, :method => :delete %> 

它工作正常。

问题是,当我删除一个音符时,属于该音符的note_category行被删除,但是没有运行destroy方法。 我知道这是因为没有运行自定义代码,并且第一行中的终端输出没有显示在终端中。 这是终端输出:

 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 

我认为通过使用:dependent =>:destroy,NoteCategories控制器中的destroy方法应该在删除之前运行。 我究竟做错了什么?

:dependent => :destroy将在模型上调用destroy方法而不是控制器

从文档 :

如果设置为:destroy将通过调用其destroy方法将所有关联对象与此对象一起销毁。

也就是说,如果你想在销毁之前为你的note_categories定制一些东西,你必须覆盖NoteCategory 模型中destroy方法,或者使用after_destroy / before_destroy回调。

无论哪种方式,使用:dependent => :destroy将永远不会执行控制器中包含的代码,这就是为什么你没有在终端中看到puts语句的输出。