0
这是什么是在轨道回调方法?当我学习控制器和模型时,我发现这个术语在任何地方都被使用。有人可以提供例子吗?什么是导轨回调方法?
这是什么是在轨道回调方法?当我学习控制器和模型时,我发现这个术语在任何地方都被使用。有人可以提供例子吗?什么是导轨回调方法?
参考ActiveRecord::Callbacks
的回调w.r.to ActiveRecord的
Callbacks are hooks into the lifecycle of an Active Record object that allow you
to trigger logic before or after an alteration of the object state. This can be
used to make sure that associated and dependent objects are deleted when destroy
is called (by overwriting before_destroy) or to massage attributes before they‘re
validated (by overwriting before_validation). As an example of the callbacks
initiated, consider the Base#save call for a new record
拿一个例子,你有一个Subscription
模型,你有一列signed_up_on
这将包含其中创建订阅的日期。对于此w/o Callbacks
,您可以在您的controller
中执行如下操作。
@subscription.save
@subscription.update_attribute('signed_up_on', Date.today)
这将完全正常,但如果你有你的应用程序中的订阅是获取创建3-4个方法。所以要实现它,你需要在所有冗余的地方重复代码。
要避免这种情况,您可以使用Callbacks
和before_create
这里回调。因此,只要你订阅的目标是让创建将今天的日期指定给signed_up_on
class Subscription < ActiveRecord::Base
before_create :record_signup
private
def record_signup
self.signed_up_on = Date.today
end
end
以下是所有的回调
after_create
after_destroy
after_save
after_update
after_validation
after_validation_on_create
after_validation_on_update
before_create
before_destroy
before_save
before_update
before_validation
before_validation_on_create
before_validation_on_update
http://api.rubyonrails.org/classes/ActiveRecord名单/Callbacks.html http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html –
我发现Rails指南解释得很好。请查看[关于回调的章节](http://guides.rubyonrails.org/active_record_validations_callbacks.html#callbacks-overview)。 – Mischa