Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single Table Inheritance not working in Rails 4 app - ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed

I have a new Rails 4 app where I created a few models in the STI configuration.

The main model is called Order and it inherits from ActiveRecord::Base. This is how it looks like:

class Order < ActiveRecord::Base
  TYPES = %w(remote local)

  scope :remotes,  -> { where(type: 'remote') }
  scope :locals,   -> { where(type: 'local') }
end

The other two models are within a folder in models/orders and they're called Remote and Local and they both inherit from Order

The orders migration file looks like this:

def change
  create_table :orders do |t|
    t.string :source_url, null: false
    t.string :final_url, null: false

    t.string :type

    t.string :category

    t.timestamps
  end
end

I also made sure I was including the models/orders dir into Rails, by doing:

config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]

Now, when I log into the console with an emptied DB and run Order.all everything is fine and I get an empty relation object. But after I create the first Remote object and try running Order.all again I get the following error:

>> Order.all
Order Load (1.0ms)  SELECT "orders".* FROM "orders"
ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate
the subclass: 'Remote'. This error is raised because the column 'type' is reserved
for storing the class in case of inheritance. Please rename this column if you didn't
intend it to be used for storing the inheritance class or overwrite
Order.inheritance_column to use another column for that information.

What is going on here? What have I done wrong?

Thanks in advance.

like image 717
rodrigoalvesvieira Avatar asked Feb 14 '23 20:02

rodrigoalvesvieira


1 Answers

In order to debug this, I'd simply and see what I learn from one of two experiments...

First, even just temporarily, move the subclasses out of the Orders folder. It may be that you have them nested in a Module, or that rails expects them to be based on the name, so the 'type' column doesn't match what you think it should.

second, I'd try creating one of the subclasses from the command line, persisting it, and seeing what ActiveRecord puts in that type column and see if it matches what you're expecting.

I suspect this has something to do with the subfolder under models and Rails' inability to find the class as the type is specifying it.

like image 139
David Bock Avatar answered Apr 20 '23 00:04

David Bock