2008-10-21 52 views
3

我有以下3个rails类,它们都存储在一个表中,使用rails的单表继承。单表继承发现问题

​​

如果我有与150 ID的StockThingTemplate那么我应该在逻辑上能够做到这一点:

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

而事实上这个工程,有时

当它工作,它会生成以下SQL查询:

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

如果它不能正常工作,它会生成以下SQL查询:

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

的SQL是做什么是应该的,但问题是,为什么会产生一组SQL一次,另一次不同。这实际上是完全相同的代码。

注:

  • 我在轨道上1.2
  • 我已经在不同的地方尝试过require 'stock_thing_template'。它要么没有效果,要么造成其他问题

回答

7

好的。事实证明,这是因为rails始终没有看到整个继承层次结构。当它重新加载每个请求中的所有项时,这解释了不一致的行为(在某些地方,before_filter可能导致模型加载,在其他地方也许不会)。

它可以通过将

require_dependency 'stock_thing_template' 

在我所有的控制器,引用这些东西的顶部固定。

More info on the rails wiki - 转到页面底部

+0

非常感谢。这也解决了我的问题! – JasonSmith 2009-05-18 10:54:05