Pivotal Labs

Main menu

Skip to primary content
Skip to secondary content
  • About
  • Case Studies
  • Team
    • Executives
    • Locations
      • San Francisco (HQ)
      • Boston
      • Boulder
      • Denver
      • London
      • Los Angeles
      • New York
  • Community
    • Blogs
    • Tech Talks
    • Events
  • Careers
    • Lifestyle
    • Principles & Practices
    • Benefits
    • FAQ
    • Apply
  • Contact
    • Press Room
    • Press Releases
    • In The News
    • Press Kit
  • All
  • Labs
  • Standup
  • Tracker

Rails finders are smart about Single Table Inheritance hierarchies

David Stevenson
Tuesday, August 25, 2009

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.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter

Add New Comment Cancel reply

Your email address will not be published.

David Stevenson

David Stevenson
San Francisco

Recent Posts

  • 03/13/13: [SF] Use postgres!
  • Standup for 2/9/2012: NP in P time? As usual, no.
  • Standup 2/6/2012: Tracker UI updates
Subscribe to David's Feed

Author Topics

agile (10)
devise (1)
ec2 (1)
engines (1)
ios (1)
activerecord (3)
inverse_of (1)
css (2)
engineyard (1)
iphone (3)
rubymine (1)
rails (5)
aws (1)
javascript (1)
xmpp (1)
gogaruco (3)
activeresource (1)
heroku (1)
solr (1)
bug (1)
patch (1)
  • About
  • Case Studies
  • Team
  • Community
  • Careers
  • Contact
  • Labs
  • Events

Contact Us

contact@pivotallabs.com
+1 415-77-PIVOT
TwitterLinkedInFacebook

Pivotal Tracker

Tracker is the award-winning agile project management tool that enables real-time collaboration around a shared, prioritized backlog.
Visit pivotaltracker.com >