我有一个笔记模型,具有以下关联
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 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方法应该在被删除之前运行。我做错了什么?
发布于 2010-08-23 22:02:29
:dependent => :destroy将在模型上调用销毁方法,而不是在控制器上调用。
从documentation
销毁如果设置为:销毁,则所有关联的对象都将通过调用其销毁方法与此对象一起销毁。
也就是说,如果您希望在销毁之前对note_categories进行自定义,则必须覆盖NoteCategory 模型中的destroy方法,或者使用after_destroy/ before _destroy回调。
无论哪种方式,使用:dependent => :destroy都不会执行控制器中包含的代码,这就是为什么在终端中看不到puts语句的输出的原因。
https://stackoverflow.com/questions/3547616
复制相似问题