可用回调
这里列出了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 callbacksafter_create
andafter_update
, no matter the order
in which the macro calls were executed.
after_initialize
和 after_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