【问题标题】::dependent => :destroy isn't calling the destroy method before the deletion?:dependent => :destroy 在删除之前没有调用destroy方法吗?
【发布时间】:2010-08-23 12:44:56
【问题描述】:

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

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 行将被删除,但销毁方法并未运行。我知道这是因为自定义代码没有运行,并且第一行的终端输出没有显示在终端中。这是终端输出:

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 Controller 中的 destroy 方法应该在它被删除之前运行。我做错了什么?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    :dependent =&gt; :destroy 将在 model 而不是 controller 上调用 destroy 方法。

    来自documentation

    如果设置为 :destroy,则所有关联的对象都会通过调用其destroy 方法与该对象一起被销毁。

    也就是说,如果您希望在销毁之前对您的 note_categories 进行自定义,则必须覆盖 NoteCategory model 中的 destroy 方法,或者使用 after_destroy/before_destroy 回调。

    无论哪种方式,使用 :dependent =&gt; :destroy 将永远不会执行包含在您的控制器中的代码,这就是您在终端中看不到 puts 语句的输出的原因。

    【讨论】:

      猜你喜欢
      • 2011-02-17
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 2014-07-29
      • 2011-08-28
      • 2016-08-07
      • 2021-09-23
      相关资源
      最近更新 更多