回调方法
- create
- create!
- destroy
- destroy!
- destroy_all
- destroy_by
- save
- save!
- save(validate: false)
- toggle!
- touch
- update_attribute
- update
- update!
- valid?
跳过回调
- decrement!
- decrement_counter
- delete
- delete_all
- delete_by
- increment!
- increment_counter
- insert
- insert!
- insert_all
- insert_all!
- touch_all
- update_column
- update_columns
- update_all
- update_counters
- upsert
- upsert_all
回调顺序
3.1 Creating an Object
- before_validation
- after_validation
- before_save
- around_save
- before_create
- around_create
- after_create
- after_save
- after_commit / after_rollback
3.2 Updating an Object
- before_validation
- after_validation
- before_save
- around_save
- before_update
- around_update
- after_update
- after_save
- after_commit / after_rollback
3.3 Destroying an Object
- before_destroy
- around_destroy
- after_destroy
- after_commit / after_rollback
回调版本改动
attribute_changed? attribute_change等方法在5.1后before_save, before_update里还可以继续用,在after_save, after_update里不能用
Rails 5.0- (before_save, before_update) | Rails 5.1+ (before_save, before_update) | Rails 5.1+ (after_save, after_update) |
---|---|---|
attribute_changed? | will_save_change_to_attribute? | saved_change_to_attribute? |
attribute_change | attribute_change_to_be_saved | saved_change_to_attribute |
attribute_was | attribute_in_database | attribute_before_last_save |
changes | changes_to_save | saved_changes |
changed? | has_changes_to_save? | saved_changes? |
changed | changed_attribute_names_to_save | saved_changes.keys |
changed_attributes | attributes_in_database | saved_changes.transform_values(&:first) |