我的代码是:
# require gems
require 'rubygems'
require 'active_record'
# Start connetion to the server
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:user => "root",
:password => "password",
:database => "data"
)
# Create the table
ActiveRecord::Schema.define do
create_table :datatable do |table|
table.column :date, :string
table.column :word, :string
table.column :website, :string
end
end
class Table < ActiveRecord::Base; end
Table.create(:date => datenow, :word => someword, :website => mywebsite)
puts "code completed"
当代码想要写入表格时,我收到错误:
path/to/mysql_adapter.rb:287:in 'query': Table 'test.tables' doesn't exist (Mysql::Error)
如果我创建一个在数据库(数据)中称为表的表,那么我的所有数据都将放入其中。我想将它写入我刚创建的表(datatable)。我该怎么做并解决错误?
答案 0 :(得分:2)
错误是预料之中的。您正在访问名为table
的表,但创建了一个名为datatable
的表。
要将Table
模型配置为使用datatable
表,请使用ActiveRecord::Base.set_table_name,如下所示:
class Table < ActiveRecord::Base
set_table_name 'datatable'
end
或者,您可以将模型重命名为Datatable。
但是,我建议你将它重命名为完全不同的东西。除非您实际存储有关表的数据,否则您的模型可能不应被称为Table
。我会想到WebsiteWord
或WordOccurrence
或者只是Word
。从长远来看,我有一种感觉,它可以帮助你减轻痛苦。