Rails -- use type column without STI?

Ruby on-RailsRuby on-Rails-3Single Table-Inheritance

Ruby on-Rails Problem Overview


I want to use a column called type without invoking Single Table Inheritance (STI) - I just want type to be a normal column that holds a String.

How can I do this without having Rails expecting me to have single table inheritance and throwing an exception of The single-table inheritance mechanism failed to locate the subclass...This error is raised because the column 'type' is reserved for storing the class in case of inheritance.?

Any ideas on how to do this?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

In Rails 3.1 set_inheritance_column is deprecated, also you can just use nil as a name, like this:

class Pancakes < ActiveRecord::Base
    self.inheritance_column = nil
    #...
end

Solution 2 - Ruby on-Rails

You can override the STI column name using set_inheritance_column:

class Pancakes < ActiveRecord::Base
    set_inheritance_column 'something_you_will_not_use'
    #...
end

So pick some column name that you won't use for anything and feed that to set_inheritance_column.

Solution 3 - Ruby on-Rails

I know this question is rather old and this deviates a bit from the question you are asking, but what I always do whenever I feel the urge to name a column type or something_type is I search for a synonym of type and use that instead:

Here are a couple alternatives: kind, sort, variety, category, set, genre, species, order etc.

Solution 4 - Ruby on-Rails

Rails 4.x

I encountered the problem in a Rails 4 app, but in Rails 4 the set_inheritance_column method does not exist at all so you can't use it.

The solution that worked for me was to disable the single table inheritance by overriding ActiveRecord’s inheritance_column method, like this:

class MyModel < ActiveRecord::Base

  private

  def self.inheritance_column
    nil
  end

end

Hope it helps!

Solution 5 - Ruby on-Rails

If you want to do this for all models, you can stick this in an initializer.

ActiveSupport.on_load(:active_record) do
  class ::ActiveRecord::Base
    # disable STI to allow columns named "type"
    self.inheritance_column = :_type_disabled
  end
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKvassView Question on Stackoverflow
Solution 1 - Ruby on-RailsValentin NemcevView Answer on Stackoverflow
Solution 2 - Ruby on-Railsmu is too shortView Answer on Stackoverflow
Solution 3 - Ruby on-RailsriiView Answer on Stackoverflow
Solution 4 - Ruby on-RailsItay GrudevView Answer on Stackoverflow
Solution 5 - Ruby on-RailsBill LipaView Answer on Stackoverflow