单表继承查找问题 [英] Single Table Inheritance find issues

查看:108
本文介绍了单表继承查找问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果我有一个带有ID的 StockThingTemplate 150 然后我应该能够做到这一点:

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

事实上这有效,有时候

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

When it works, it generates the following SQL query:

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

当它不起作用时,它会生成以下SQL查询:

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

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

sql正在做它应该做的事情,但问题是,为什么它一次生成一组SQL,另一次生成另一组。它实际上是完全相同的代码。

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.

注意:


  • 我在rails 1.2

  • 我已经在各个地方试过 require'stock_thing_template'。它要么没有效果,要么导致其他问题

  • 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

推荐答案

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

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).

可以通过以下方式修复

require_dependency 'stock_thing_template'

位于引用这些内容的所有控制器的顶部。

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

有关rails wiki的更多信息 - 请转到页面底部

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

这篇关于单表继承查找问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆