Rails 单表继承 - 显式设置类型的最佳方法是什么? [英] Rails Single Table Inheritance - What is the best way to explicitly set type?
问题描述
我在 Rails 应用程序中使用 单表继承,并且想要显式设置实例的类型.
I am using single table inheritance in my rails application, and want to explicitly set the type of an instance.
我有以下内容;
class Event < ActiveRecord::Base
class SpecialEvent < Event
通过单表继承实现.
SpecialEvent.new
按预期工作,但我希望能够执行类似
SpecialEvent.new
works as expected, but I want to be able to do things like
Event.new(:type => 'SpecialEvent')
因此我可以在应用程序中轻松创建不同的子类型.
So I can create different sub_types easily in the application.
但是这不起作用,似乎将 :type
设置为 nil
,而不是我设置的值;我怀疑这是因为通过调用 Event.new
它覆盖了 :type
参数.
However this doesn't work and seems to set :type
to nil
, not the value I set it to; I suspect this is because by calling Event.new
it is overwriting the :type
argument.
有没有人有这样做的好方法?
Has anyone got a good way of doing this?
推荐答案
如果您尝试动态实例化一个子类型,并且您将该类型作为字符串,您可以这样做:
If you're trying to dynamically instantiate a subtype, and you have the type as a string, you can do this:
'SpecialEvent'.constantize.new()
这篇关于Rails 单表继承 - 显式设置类型的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!