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

时间:2010-08-23 12:44:57

标签: ruby-on-rails

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

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

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

<%= button_to 'Remove', note_category, :confirm => '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 =&gt; :destroy,NoteCategories控制器中的destroy方法应该在删除之前运行。我做错了什么?

1 个答案:

答案 0 :(得分:4)

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

来自documentation

  

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

也就是说,如果您想要在销毁之前为自己的note_categories设置自定义内容,则必须覆盖NoteCategory 模型中的destroy方法,或者使用after_destroy / before_destroy回调。

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