在工作中发现,rails guide与其他资料中对ActiveRecord的回调顺序不太一致,因此做一个实验来确定创建、修改、删除、touch所触发的回调及顺序。 测试代码

class Product < ActiveRecord::Base

  [:before_validation,:after_validation,
   :before_save,
   #:around_save,
   :before_create,
   #:around_create,
   :after_create,:before_update,:around_update,
   :after_update,:after_save,:before_destroy,
   :after_destroy,:after_touch].each do |m|
     define_method m do
       logger.info "#{m} execute"
     end
     eval "#{m} :#{m}"
   end

end

create结果

0.webp

update结果

1.webp

destroy 结果

2.webp

touch结果

3.webp

测试使用的ruby版本为2.2.3,rails版本为4.2.4,around_save和around_create会导致commit失败,目前不知原因,估计为rails的bug,综上真实的结果为

  • create触发的回调(按顺序)before_validation、after_validation、before_save、before_create、after_create、after_save

  • update触发的回调 before_validation、after_validation、before_save、before_update、around_update、after_update、after_save

  • destroy触发的回调 before_destroy、after_destroy

  • touch触发的回调 after_touch ##费了半天功夫,rails guide是对的!