[英]“ActiveRecord::StatementInvalid: Could not find table” in rails model inheritance
When I run 当我跑步
irb(main):003:0> House.new(name: "A house")
I get the error 我得到错误
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'
...
You can see my code below 您可以在下面看到我的代码
property.rb property.rb
class Property < ApplicationRecord
self.abstract_class = true
end
apartment.rb apartment.rb
class Apartment < Property
end
house.rb house.rb
class House < Property
end
db/migrate/20160616022800_create_properties.rb 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
And the properties table was created via rake db:migrate
属性表是通过
rake db:migrate
创建的 Note : I'm using rails 5.0.0.rc1
注意 :我正在使用rails 5.0.0.rc1
What am I doing wrong? 我究竟做错了什么?
I believe you need to remove the self.abstract_class
line from your Property
model. 我相信您需要从
Property
模型中删除self.abstract_class
行。
Adding abstract_class
to the model will force child classes to bypass the implied STI table naming of the parent class Property
. 向模型添加
abstract_class
将迫使子类绕过父类Property
的隐式STI表命名。 Essentially, we're saying Property
can no longer be instantiated, and is not backed by a database table. 本质上,我们说的是
Property
不能再实例化,并且不再由数据库表支持。
Therefore, child classes of Property
are not going to look to the parent class for the table name, they will look for a table based on their own class name. 因此,
Property
子类不会在父类中查找表名,而是会基于自己的类名来查找表。
Alternatively, you could set self.table_name = 'properties'
in your Property
model and that should work. 另外,您可以在
Property
模型中设置self.table_name = 'properties'
,这应该可以工作。 However, this defeats the purpose of defining an abstract_class
. 但是,这违反了定义
abstract_class
的目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.