Ruby on Rails Callback, what is difference between :before_save and :before_create?

倖福魔咒の 提交于 2019-12-28 03:15:11

问题


Could you explain in detail what the :before_save and :before_create Ruby on Rails callbacks are, and what they have to do with Rails validations? Does validation occur after :before_save or :before_create?


回答1:


In a create operation under Rails, there are six callbacks before the database operation, and two after. In order, these are:

  1. before_validation
  2. before_validation_on_create
  3. after_validation
  4. after_validation_on_create
  5. before_save
  6. before_create

    DATABASE INSERT
  7. after_create
  8. after_save

Update operations have exactly the same set, except read update instead of create everywhere (and UPDATE instead of INSERT).

From this, you can see that validation is carried out before the before_save and before_create callbacks.

The before_save occurs slightly before the before_create. To the best of my knowledge, nothing happens between them; but before_save will also fire on Update operations, while before_create will only fire on Creates.




回答2:


before_save is called every time an object is saved. So for new and existing objects. (create and update action)

before_create only before creation. So only for new objects (create action)




回答3:


before_create vs before_save :on => :create

Sometimes you have to be careful of the order of the callbacks

See here for more details: http://pivotallabs.com/activerecord-callbacks-autosave-before-this-and-that-etc/



来源:https://stackoverflow.com/questions/6249475/ruby-on-rails-callback-what-is-difference-between-before-save-and-before-crea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!