【发布时间】: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