【问题标题】:Single Table Inheritance find issues单表继承发现问题
【发布时间】:2008-10-21 02:34:42
【问题描述】:

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

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

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

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'。它要么没有效果,要么导致其他问题

【问题讨论】:

    标签: ruby-on-rails ruby inheritance


    【解决方案1】:

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

    可以通过放置来修复

    require_dependency 'stock_thing_template'
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多