为什么在 Rails 模型类中可以调用回调? [英] Why are callbacks callable in Rails model classes?

查看:47
本文介绍了为什么在 Rails 模型类中可以调用回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 Rails 模型类:

I have a Rails model class like this:

class Something < ActiveRecord::Base

  before_create do
     self.key = SecureRandom.urlsafe_base64(8)
  end

end

为什么我可以在这里调用 before_create ?我希望它是 ActiveRecord::Base 的一种方法,但它不是.回调是 ActiveRecord::Callbacks 的方法.但是为什么我可以在模型类中调用它们而不包含一些东西?

Why can I call before_create here? I expected it to be a method of ActiveRecord::Base but it is not. Callbacks are methods of ActiveRecord::Callbacks. But why can I call them in a model class without including something?

推荐答案

你可以这样做,因为 ActiveRecord::Base 这样做(或类似的东西,取决于你的 Rails 版本):

You can do that because ActiveRecord::Base does this (or something similar depending on your version of Rails):

Base.class_eval do
  #...
  include Callbacks, ActiveModel::Observing, Timestamp
  #...
end

所以 ActiveRecord::Base 已经包含了 ActiveRecord::Callbacks 并且您的类通过从 ActiveRecord::Base 继承来获取回调.

So ActiveRecord::Base already includes ActiveRecord::Callbacks and your class picks up the callbacks by inheriting from ActiveRecord::Base.

这篇关于为什么在 Rails 模型类中可以调用回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆