簡體   English   中英

Rails模型繼承中的“ ActiveRecord :: StatementInvalid:找不到表”

[英]“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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM