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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With