2016-06-17 46 views
0

當我運行「的ActiveRecord :: StatementInvalid:找不到表」,在鐵軌模型繼承

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 

分貝/遷移/ 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 enter image description here 注意:我使用的軌道5.0.0.rc1

我在做什麼錯?

+1

您是否嘗試過沒有'Property'作爲抽象類? – treiff

+0

我不明白爲什麼,但它的作品!謝謝!在領域問題中,屬性是一個抽象的概念 –

回答

1

我相信你需要從Property模型中刪除self.abstract_class行。

abstract_class添加到模型將強制子類繞過父類Property的隱含的STI表命名。本質上,我們說Property不能再實例化,並且不支持數據庫表。

因此,Property的子類不會查找表名的父類,它們將根據它們自己的類名查找表。

或者,您可以在您的Property模型中設置self.table_name = 'properties',這應該有效。但是,這違背了定義abstract_class的目的。