什么是Rails中ActiveRecord :: Base的回调类

时间:2013-03-10 07:40:39

标签: ruby ruby-on-rails-3.2

有人可以在本指南http://guides.rubyonrails.org/active_record_validations_callbacks.html

中解释16个回调课程

2 个答案:

答案 0 :(得分:1)

好的,我想我理解你的问题:

PictureFileCallbacks中的after_destroy方法将由rails自动调用:

当rails破坏你的PictureFile对象时,它会实例化一个PictureFileCallbacks对象,并尝试在其中运行after_destroy方法。

一切按照惯例运作,如果你正确地遵循命名,一切都将开箱即用。

在虚拟项目上尝试一下,如果你在制作这项工作时遇到一些麻烦,请回来查看一些代码。

答案 1 :(得分: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"]