Inheritance of individual tables

I have the following 3 rails classes that are all stored in the same table using rails Single Table inheritance.

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

If I have a StockThingTemplate with ID 150 , then I should logically execute this:

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

And actually it 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 does not work, it generates the following SQL query:

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

sql does what it should, but the question is WHY it generates one SQL set once and another set at another time. This is literally the same code.

Notes:

  • I'm on the rails 1.2
  • I already tried require 'stock_thing_template' in different places. This either has no effect or causes other problems.
+3
source share
1 answer

OK It turns out that this is because the rails do not always see the entire hierarchy of inheritance. Since it reloads all the elements in each request, this explains the inconsistent behavior (in some places the before_filter file probably caused the models to load, in other places it may not).

It can be fixed by setting

 require_dependency 'stock_thing_template' 

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

For more information on the rails wiki , go to the bottom of the page.

+7
source

Source: https://habr.com/ru/post/1277725/


All Articles