从 Rails 的单表继承中获取子类的列表/数组? [英] Get a list/array of child classes from Single Table Inheritance in Rails?

查看:53
本文介绍了从 Rails 的单表继承中获取子类的列表/数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一大堆子类,它们通过我的 Rails 应用程序中的单表继承从父类继承.我想要一种方法来获取从主类继承的所有子类的数组.

I have a whole bunch of child classes that inherit from a parent class via single-table-inheritance in my Rails app. I'd like a way to get an array of all the child classes that inherit from the main class.

我尝试了在另一个 SO 答案中找到的以下单链接命令,但它只返回父类.

I tried the following single-link command that I found in another SO answer, but it only returns the parent class.

ObjectSpace.each_object(class<<MyParentClass;self;end)

有什么干净的方法可以做到这一点吗?

Is there any clean way to do this?

显然,Rails 在 Dev 模式下调用时只会延迟加载子类,并且可能会根据 Rails 版本进行生产.但是,第一个答案应该适用于生产模式下的 Rails 3.1 及更高版本.

Apparently Rails only lazy-loads child classes when called in Dev mode, and possibly production depending on the Rails version. However, the first answer should work on Rails 3.1 and higher in Prod mode.

推荐答案

假设表中每个对象至少有一个:

Assuming there is at least one of each of object extant in the table:

Object.all.uniq{|x| x.type}.collect(&:type)

这篇关于从 Rails 的单表继承中获取子类的列表/数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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