Rails STI - 防止基类实例化 [英] Rails STI - Prevent base class from instantiation

查看:35
本文介绍了Rails STI - 防止基类实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当基类被实例化时,在 Rails STI 情况下有什么方法可以抛出错误吗?覆盖 initialize 会做到这一点,但随后会渗透到子类中.

Is there any way in a Rails STI situation to throw an error when the base class is Instantiated? Overriding initialize will do it but then that gets trickled down to the subclasses.

谢谢

推荐答案

John Topley 的回答实际上是错误的.在基类中设置 abstract_class = true 实际上会导致子类自动停止设置它们的类型.另外,除非您在基类中设置_table_name,否则子类会抱怨他们的表不存在.

The answer by John Topley is actually wrong. Setting abstract_class = true in the base class will actually cause the child classes to stop setting their type automatically. Plus, unless you set_table_name in the base class, the child classes will complain their table does not exist.

这是因为 abstract_class=true 的目的是在您不使用 STI 时设置继承,并且希望在 ActiveRecord::Base 和一个或多个模型类.

This is because the purpose of abstract_class=true is to set up inheritance when you are NOT using STI, and want to have an abstract class (class not backed by a db table) in your class hierarchy between ActiveRecord::Base and one or more model classes.

初始化 raise 是一种解决方案,将 validates_presence_of :type 添加到基类也是一种解决方案.

Having initialize raise is one solution, also adding validates_presence_of :type to the base class is a solution.

注意,如果你重写了初始化,你需要调用 super:

Note if you DO override initialize, you need to call super:

def initialize(*args)
  raise "Cannot directly instantiate an AbstractUser" if self.class == AbstractUser
  super
end

这篇关于Rails STI - 防止基类实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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