Rails 4 active record 回调

可用回调

这里列出了Active Record所有回调方法和对应的操作:

创建一个对象

before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save

更新对象

before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save

删除对象

before_destroy
around_destroy
after_destroy

after_save 在更新和创建之后都会运行, but always after the more
specific callbacks after_create and after_update, no matter the order
in which the macro calls were executed.

after_initializeafter_find

class User < ActiveRecord::Base
  after_initialize do |user|
    puts "You have initialized an object!"
  end

  after_find do |user|
    puts "You have found an object!"
  end
end

>> User.new
You have initialized an object!
=> #<User id: nil>

>> User.first
You have found an object!
You have initialized an object!
=> #<User id: 1>

after_touch

用于在创建active record对象之后

class User < ActiveRecord::Base
  after_touch do |user|
    puts "You have touched an object"
  end
end

>> u = User.create(name: 'Kuldeep')
=> #<User id: 1, name: "Kuldeep", created_at: "2013-11-25 12:17:49", updated_at: "2013-11-25 12:17:49">

>> u.touch
You have touched an object
=> true

逻辑回调

调用:if和:unless可以使用Symbol或者字符串

class Order < ActiveRecord::Base
  before_save :normalize_card_number, if: :paid_with_card?
end

或者

class Order < ActiveRecord::Base
  before_save :normalize_card_number, if: "paid_with_card?"
end

Using :if and :unless with a Proc

    原文作者:天赢金创
    原文地址: https://segmentfault.com/a/1190000000488584
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞