应用程序/模型
class Amodel < ActiveRecord::Base
end
class Bmodel < Amodel
end
class Cmodel < Bmodel
end
DB /迁移
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 回答
由于ActiveRecord STI的构建方式 . 加载类时,它会向其父级注册(请参阅#inherited钩子) . 因此,当您调用Amodel#find或Bmodel #find时,如果尚未找到子类't known, it can' .
在 生产环境 中,这个问题不明显,因为Rails会在启动时加载所有模型,从而防止出现这种问题 .