Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Single Table Inheritance - What is the best way to explicitly set type?

I am using single table inheritance in my rails application, and want to explicitly set the type of an instance.

I have the following;

class Event < ActiveRecord::Base
class SpecialEvent < Event

which is implemented through single table inheritance.

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.

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?

like image 310
DanSingerman Avatar asked Jan 12 '09 15:01

DanSingerman


1 Answers

If you're trying to dynamically instantiate a subtype, and you have the type as a string, you can do this:

'SpecialEvent'.constantize.new()
like image 146
Codebeef Avatar answered Oct 21 '22 00:10

Codebeef