[英]“ActiveRecord::StatementInvalid: Could not find table” in rails model inheritance
当我跑步
irb(main):003:0> House.new(name: "A house")
我得到错误
ActiveRecord::StatementInvalid: Could not find table 'houses'
from /home/overflow012/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.rc1/lib/active_record/connection_adapters/sqlite3_adapter.rb:429:in `table_structure'
...
您可以在下面看到我的代码
property.rb
class Property < ApplicationRecord
self.abstract_class = true
end
apartment.rb
class Apartment < Property
end
house.rb
class House < Property
end
db / migrate / 20160616022800_create_properties.rb
class CreateProperties < ActiveRecord::Migration[5.0]
def change
create_table :properties do |t|
t.string :name
t.string :detail
t.float :price
t.string :type
t.timestamps
end
end
end
属性表是通过rake db:migrate
创建的 注意 :我正在使用rails 5.0.0.rc1
我究竟做错了什么?
我相信您需要从Property
模型中删除self.abstract_class
行。
向模型添加abstract_class
将迫使子类绕过父类Property
的隐式STI表命名。 本质上,我们说的是Property
不能再实例化,并且不再由数据库表支持。
因此, Property
子类不会在父类中查找表名,而是会基于自己的类名来查找表。
另外,您可以在Property
模型中设置self.table_name = 'properties'
,这应该可以工作。 但是,这违反了定义abstract_class
的目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.