活动记录无法找到表格

时间:2016-01-10 20:30:00

标签: ruby activerecord

我正在学习Active Record,并在下面写了一个简单的例子:

#!/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 个答案:

答案 0 :(得分:1)

您的数据库没有networks表。因此,ActiveRecord会在尝试保留您的数据时抛出该错误。

您应该使用create_table方法来创建表格。

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