我正在学习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>'
我做错了什么?
答案 0 :(得分:1)
您的数据库没有networks
表。因此,ActiveRecord会在尝试保留您的数据时抛出该错误。
您应该使用create_table方法来创建表格。
create_table(:networks) do |t|
t.column :name, :string
end