0

Rails 中的回调方法到底是什么?当我了解控制器和模型时,我看到这个术语无处不在。有人可以提供例子吗?

4

1 回答 1

3

ActiveRecord::Callbacks回调 wrto 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 个方法可以创建订阅。因此,要实现它,您必须在所有多余的地方重复代码。

为避免这种情况,您可以在此处使用Callbacksbefore_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
于 2012-10-24T15:08:23.580 回答