rails中的回调方法是什么?

时间:2012-10-24 14:34:21

标签: ruby-on-rails ruby ruby-on-rails-3

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

1 个答案:

答案 0 :(得分:3)

回复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个方法可以创建订阅。因此,要实现它,您需要在所有冗余的地方重复代码。

为避免这种情况,您可以在此处使用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
相关问题