简体   繁体   中英

“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

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

And the properties table was created via rake db:migrate 在此处输入图片说明 Note : I'm using 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.

Adding abstract_class to the model will force child classes to bypass the implied STI table naming of the parent class Property . Essentially, we're saying Property can no longer be instantiated, and is not backed by a database table.

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.

Alternatively, you could set self.table_name = 'properties' in your Property model and that should work. However, this defeats the purpose of defining an abstract_class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM