为什么 Rails 5 使用 ApplicationRecord 而不是 ActiveRecord::Base? [英] Why Rails 5 uses ApplicationRecord instead of ActiveRecord::Base?

查看:36
本文介绍了为什么 Rails 5 使用 ApplicationRecord 而不是 ActiveRecord::Base?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,Rails 5 添加了 ApplicationRecord 作为我们的模型 (ActiveRecord) 继承的抽象类.

We know that Rails 5 added ApplicationRecord as an abstract class which was inherited by our models (ActiveRecord).

但基本上,我认为我们用 ApplicationRecord 做的每一个技术要求,我们也可以用 ActiveRecord::Base 来做.例如:

But basically, I think every technical requirement we do with ApplicationRecord, we can also do with ActiveRecord::Base. For instance:

module MyFeatures
  def do_something
    puts "Doing something"
  end
end

class ApplicationRecord < ActiveRecord::Base
  include MyFeatures
  self.abstract_class = true
end

所以现在每个模型都将附加 MyFeatures 的行为.但我们也可以在 Rails 4 中实现这一点:

So now every model will be attached the behaviors of MyFeatures. But we can also achieve this in Rails 4:

ActiveRecord::Base.include(MyFeatures)

那么使用ApplicationRecord有什么好处,你觉得有必要添加ApplicationRecord吗?

So what is the benefit of using ApplicationRecord, do you think it is necessary to add ApplicationRecord?

推荐答案

虽然在基本的 Rails 应用程序中看起来是一样的,但一旦你开始使用 Rails 引擎、插件/gems 或来自 <代码>ActiveRecord::Base.

While it may seem the same in basic Rails applications, there actually is an important difference once you begin to use rails engines, plugins / gems or direct methods from ActiveRecord::Base.

  • ActiveRecord::Base.include(MyFeatures) 将特性直接混合到 ActiveRecord::Base 中,并且它永远存在于那里供以后使用ActiveRecord::Base(它不能被unmixed")并且在包含之后的任何代码中都无法再获得原始的 ActiveRecord::Base .如果某些混合功能更改了默认的 ActiveRecord 行为,或者例如两个引擎/gem 试图包含同名方法.

  • ActiveRecord::Base.include(MyFeatures) mixes in the features directly into ActiveRecord::Base and it is present there forever for all later uses of ActiveRecord::Base (it cannot be "unmixed") and there is no way to get the original ActiveRecord::Base anymore in any code after the include. This can easily lead to problems if some of the mixed in feature changed the default ActiveRecord behavior or if e.g. two engines / gems tried to include same-named methods.

另一方面,ApplicationRecord 方法使特性仅针对从它继承的类(模型)、其他类以及直接使用 ActiveRecord::Base 保持原始状态,不受模块功能的影响.

On the other hand, the ApplicationRecord approach makes the features present only for the classes (models) that inherit from it, other classes, as well as direct use of ActiveRecord::Base stay pristine, uncluttered by the module features.

这在使用引擎或 Rails 插件时尤为重要,因为它允许它们将自己的模型逻辑与主应用程序的模型逻辑分开,而这在 ApplicationRecord 之前是不可能的.

This is especially important when engines or rails plugins are used as it allows them to separate their own model logic from the main application's model logic which was not possible before ApplicationRecord.

所有这些也在这篇博文这个 github 评论.

这篇关于为什么 Rails 5 使用 ApplicationRecord 而不是 ActiveRecord::Base?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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