有人可以解释本指南中的 16 个回调类吗http://guides.rubyonrails.org/active_record_validations_callbacks.html
问问题
442 次
2 回答
1
好的,我想我理解你的问题:
PictureFileCallbacks 中的 after_destroy 方法将被 rails 自动调用:
当 rails 销毁您的 PictureFile 对象时,它会实例化一个 PictureFileCallbacks 对象并尝试在其中运行 after_destroy 方法。
一切都按惯例工作,如果你正确地遵循命名,一切都会开箱即用。
在一个虚拟项目上试一试,如果你在做这项工作时遇到问题,请返回一些代码来显示。
于 2013-03-10T08:13:17.187 回答
0
一切都按约定进行,您可以尝试以下示例:
#generate PictrueFile model with name attribute and generate seed
rails g model PictureFile name:string
#seeds.rb
3.times do |i|
PictureFile.create(name: "name#{i}")
end
#create picture_file.rb and picture_file_callbacks.rb in model directory
#picture_file_callbacks.rb
class PictureFileCallbacks
def after_destroy(picture_file)
PictureFile.create(name: "demo")
end
end
#picture_file_callbacks.rb
class PictureFile < ApplicationRecord
after_destroy PictureFileCallbacks.new
end
execute the command in rails c
PictureFile.first.destroy
PictrueFile.pluck(:name) #=>["name1", "name2", "demo"]
于 2017-06-07T02:47:03.423 回答