ActiveRecord :: Base#find在单表继承(STI)中不返回任何记录

时间:2010-08-09 03:55:49

标签: ruby-on-rails activerecord sti

应用程序/模型

class Amodel < ActiveRecord::Base
end

class Bmodel < Amodel
end

class Cmodel < Bmodel  
end

分贝/迁移

create_table :amodels do |t|
  t.string :type
end

在脚本/控制台上......

$ script/console
Loading development environment (Rails 2.3.4)
>> Cmodel.create
=> #<Cmodel id: 1, type: "Cmodel">
>> Bmodel.find(:all)
=> [#<Cmodel id: 1, type: "Cmodel">]

好的,但是Bmodel在重启控制台之后没有返回任何记录,如:

>> exit
$ script/console
Loading development environment (Rails 2.3.4)
>> Bmodel.find(:all)
=> []

但是,它在访问Cmodel之后有效:

>> Cmodel
=> Cmodel(id: integer, type: string)
>> Bmodel.find(:all)
=> [#<Cmodel id: 1, type: "Cmodel">]

Amodel的工作方式如下:

>> exit
$ script/console
Loading development environment (Rails 2.3.4)
>> Amodel.find(:all)
=> [#<Cmodel id: 1, type: "Cmodel">]

有谁知道它为什么会这样?

Rails:2.3.4
Ruby:1.8.7
操作系统:Ubuntu 9.0.4

1 个答案:

答案 0 :(得分:2)

由于ActiveRecord STI的构建方式。加载类时,它会向其父级注册(请参阅#inherited挂钩)。因此,当你调用Amodel#find或Bmodel#find时,如果子类未知,则无法找到它。

在生产中,这个问题不明显,因为Rails会在启动时加载所有模型,防止出现这种问题。

相关问题