2016-01-10 77 views
1

我學習活動記錄,並在下面寫一個簡單的例子:活動記錄找不到表

#!/usr/bin/ruby 

    require 'active_record' 
    require 'sqlite3' 

    ActiveRecord::Base.establish_connection(
     adapter: 'sqlite3', 
     database: 'test.sqlite3', 
    ) 

    class Network < ActiveRecord::Base 
    end 

    network = Network.create(name: "Network1") 

    puts Network.all 

但是這導致的錯誤消息:

/var/lib/gems/2.1.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/sqlite3_adapter.rb:511:in `table_structure': Could not find table 'networks' (ActiveRecord::StatementInvalid) 
    from /var/lib/gems/2.1.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/sqlite3_adapter.rb:385:in `columns' 
    from /var/lib/gems/2.1.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/schema_cache.rb:43:in `columns' 
    from /var/lib/gems/2.1.0/gems/activerecord-4.2.5/lib/active_record/attributes.rb:93:in `columns' 
    from /var/lib/gems/2.1.0/gems/activerecord-4.2.5/lib/active_record/attributes.rb:98:in `columns_hash' 
    from /var/lib/gems/2.1.0/gems/activerecord-4.2.5/lib/active_record/inheritance.rb:205:in `subclass_from_attributes?' 
    from /var/lib/gems/2.1.0/gems/activerecord-4.2.5/lib/active_record/inheritance.rb:54:in `new' 
    from /var/lib/gems/2.1.0/gems/activerecord-4.2.5/lib/active_record/persistence.rb:33:in `create' 
    from test.rb:14:in `<main>' 

我在做什麼錯?

回答

1

您的數據庫沒有networks表。因此ActiveRecord會在嘗試保存數據時拋出該錯誤。

您應該使用create_table方法來創建表格。

create_table(:networks) do |t| 
    t.column :name, :string 
end 
+0

我以爲它自然會這麼做?如果你想覆蓋它,你只需要定義列名稱?我不想這樣做。 – user5603796

+0

@ user5603796您正在使用關係數據庫。因此,預計在使用表格之前,您的所有字段都已定義。要定義你的領域,你必須創建你的表格。總之,在使用它之前,您必須使用所有的字段(和類型)來定義您的表格 –

+0

文檔說只有當您要覆蓋默認值時才這樣做。我不明白 – user5603796