Michoel Samuels

November 18, 2024

Rails: Be careful when naming a column "type"

Be careful when naming your Active Record columns.

If you name a model column`type`, Rails will silently assume you’re using STI (Single Table Inheritance).

This causes all sorts of strange behavior, including breaking your fixtures and modifying all of Active Record’s generated SQL.

Here's the normal SQL that Active Record is supposed to generate:

User.all
# => SELECT users.* FROM users

But here what it generates instead:

User.all
# => SELECT users.* FROM users WHERE users.type = 'users'

I use the `type` column for other things, nor can I rename it.
What's the fix?

ChatGPT suggested explicitly opting out of STI on the model:

class User < ApplicationRecord
  self.inheritance_column = nil:
end

That led me to this Stack Overflow answer, which suggested opting out of STI for the whole project:

class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class
  # disable STI to allow columns named "type"
  self.inheritance_column = :_type_disabled
end

Problem solved!

It's a little frustrating that STI isn't opt-in. 
Having a bunch of weird features kick in unexpectedly doesn't seem like "optimizing for programmer happiness".

But I'm glad there are decades of Ruby content online, so LLMs have tons of material to work with.
This would have taken hours more without them.

Cheers!