单表继承查找问题

3
我有以下3个Rails类,它们都存储在同一个表中,使用Rails的单表继承。
class Template < ActiveRecord::Base
class ThingTemplate < Template
class StockThingTemplate < ThingTemplate

如果我有一个ID为150的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,而另一次会生成不同的一组。这段代码完全相同。

注:

  • 我使用的是Rails 1.2
  • 我已经尝试在不同的位置使用require 'stock_thing_template',但要么没有效果,要么会导致其他问题。
1个回答

7

好的。事实证明这是因为Rails并不总是看到整个继承层次结构。由于它在每个请求上重新加载所有项目,这解释了不一致的行为(在某些地方,before_filter可能会导致模型加载,在其他地方可能不会)。

可以通过添加以下代码来解决:

require_dependency 'stock_thing_template'

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

更多信息请参考Rails维基 - 转到页面底部


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接