Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails STI - Prevent base class from instantiation

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.

Thanks

like image 471
Jake Avatar asked May 17 '10 15:05

Jake


1 Answers

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.

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.

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

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 
like image 174
Michael Johnston Avatar answered Sep 18 '22 21:09

Michael Johnston