Ruby on Rails 回调,:before_save 和:before_create 之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6249475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:20:02  来源:igfitidea点击:

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

ruby-on-railsrubyruby-on-rails-3validation

提问by Agung Prasetyo

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

能不能详细解释一下什么是:before_save:before_createRuby on Rails的回调是,他们有使用Rails验证该怎么办?验证是否发生在:before_save或之后:before_create

回答by Chowlett

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

在 Rails 下的创建操作中,数据库操作之前有六个回调,之后有两个。按顺序,这些是:

  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
  1. before_validation
  2. before_validation_on_create
  3. after_validation
  4. after_validation_on_create
  5. before_save
  6. before_create

    数据库插入
  7. after_create
  8. after_save

Update operations have exactly the same set, except read updateinstead of createeverywhere (and UPDATEinstead of INSERT).

更新操作具有完全相同的设置,除了读取update而不是create无处不在(以及UPDATE而不是INSERT)。

From this, you can see that validation is carried out before the before_saveand before_createcallbacks.

由此可以看出,验证是在before_savebefore_create回调之前进行的。

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

before_save之前的略微发生before_create。据我所知,他们之间什么也没有发生。但before_save也会触发更新操作,而before_create只会触发创建。

回答by Michael Koper

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

before_save每次保存对象时都会调用。所以对于新的和现有的对象。(创建和更新操作)

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

before_create仅在创建之前。所以仅适用于新对象(创建操作)

回答by 23inhouse

before_createvs before_save :on => :create

before_create对比 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/

有关更多详细信息,请参见此处:http: //pivotallabs.com/activerecord-callbacks-autosave-before-this-and-that-etc/