Active Record Callbacks

所有的callback:

3.1 Creating an Object

3.2 Updating an Object

3.3 Destroying an Object

callback用于注册:

class User < ApplicationRecord
  validates :login, :email, presence: true
  before_validation :ensure_login_has_a_value
  private
    def ensure_login_has_a_value
      if login.nil?
        self.login = email unless email.blank?
      end
    end
end

如果块内的代码太短以至于它适合一行,请考虑使用这种样式

class User < ApplicationRecord
  validates :login, :email, presence: true
  before_create do
    self.name = login.capitalize if name.blank?
  end
end
注意:callback必须放在private方法中:

class User &lt; ApplicationRecord<br />
&nbsp; validates :login, :email, presence: true

&nbsp; before_validation :ensure_login_has_a_value

&nbsp; private
&nbsp;&nbsp;&nbsp; def ensure_login_has_a_value
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if login.nil?
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.login = email unless email.blank?
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end
&nbsp;&nbsp;&nbsp; end
end

The following methods trigger callbacks:

  • create
  • create!
  • destroy
  • destroy!
  • destroy_all
  • destroy_by
  • save
  • save!
  • save(validate: false)
  • toggle!
  • touch
  • update_attribute
  • update
  • update!
  • valid?

Additionally, the

after_find
callback is triggered by the following finder methods:

  • all
  • first
  • find
  • find_by
  • find_by_*
  • find_by_*!
  • find_by_sql
  • last

跳过callback:

  • 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

Relational Callbacks

删除后进行调用:

class User &lt; ApplicationRecord
&nbsp; has_many :articles, dependent: :destroy
end
class Article &lt; ApplicationRecord
&nbsp; after_destroy :log_destroy_action
&nbsp; def log_destroy_action
&nbsp;&nbsp;&nbsp; puts &#39;Article destroyed&#39;
&nbsp; end
end

验证:

user = User.first
user.articles.create!
user.destroy

8个条件回调(进官网看吧)