Rails finders are smart about Single Table Inheritance hierarchies

August 25, 2009 David Stevenson

When creating associations to classes that use Single Table Inheritance (STI), rails is smarter about the hierarchy than I would have expected. A call to find on a base class yields a query that does not filter on type. But what about a call to find on a subclass? Instead of making a single filter on type, rails finds all the subclasses of that subclass and creates an “OR” expression in the “WHERE” clause.

Generated SQL respects class heirarchy

# ActiveRecord::Base < User < Admin < SuperAdmin
something.admin    # has_one :admin

Generates the following SQL:

# SELECT * FROM users WHERE (type = 'Admin' OR type = 'SuperAdmin')

When it doesn’t work

Since it relies on the class hierarchy, the query is only accurate if every subclass has been loaded. If class preloading is off, for example, very weird things can happen. The query will depend non-deterministically on which subclasses have been loaded.

About the Author


New Version of Tweed: 0.9.14 Now Available
New Version of Tweed: 0.9.14 Now Available

0.9.14 of Tweed is now available in the App Catalog. Bugs: timeout didn't actually timeout re-launch app ...


I just spent a wonderful weekend with 75 of the brightest folks I know in the Ruby community. My hat's off ...

SpringOne 2021

Register Now