views:

288

answers:

1

I have the following 3 rails classes, which are all stored in one table, using rails' Single table inheritance.

class Template < ActiveRecord::Base
class ThingTemplate < Template
class StockThingTemplate < ThingTemplate

If I have a StockThingTemplate with ID of 150 then I should logically be able to do this:

ThingTemplate.find(150)
=> #returns me the StockThingTemplate

And in fact this works, sometimes

When it works, it generates the following SQL query:

SELECT * FROM templates WHERE (templates.`id` = 159) AND ( (templates.`type` = 'ThingTemplate') OR (templates.`type` = 'StockThingTemplate' ) )

When it doesn't work, it generates the following SQL query:

SELECT * FROM templates WHERE (templates.`id` = 159) AND ( (templates.`type` = 'ThingTemplate') )

The sql is doing what it is supposed to, but the question is, WHY is it generating one set of SQL one time, and a different set another time. It's literally the exact same code.

Notes:

  • I'm on rails 1.2
  • I've already tried require 'stock_thing_template' in various places. It either has no effect, or causes other problems
+6  A: 

OK. Turns out this is because rails doesn't see the entire inheritance hierarchy all the time. As it reloads all the items on every request, this explains the inconsistent behaviour (in some places a before_filter was probably causing the models to load, in other places maybe not).

It can be fixed by putting

require_dependency 'stock_thing_template'

at the top of all my controllers that reference those things.

More info on the rails wiki - go to the bottom of the page

Orion Edwards
Thank you very much. This solved my problem as well!
jhs