开发者

MySQL active record problem writing to newly created table

My code is:

# 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, :wo开发者_如何学Gord => someword, :website => mywebsite)
puts "code completed"

And I get an error when the code wants to write to the table saying:

path/to/mysql_adapter.rb:287:in 'query': Table 'test.tables' doesn't exist (Mysql::Error)

If I create a table that is called tables within the database (data) then all of my data is put into there. I want to it to be written to the table (datatable) I have just created. How can I do this and solve the error?


The error is to be expected. You're accessing a table called table, but creating a table called datatable.

To configure your Table model to use the datatable table, use ActiveRecord::Base.set_table_name like so:

class Table < ActiveRecord::Base
  set_table_name 'datatable'    
end

Alternatively, you could rename your model to Datatable.

However, I'd suggest you rename it to something entirely different. Unless you're actually storing data about tables, your model probably shouldn't be called Table. WebsiteWord comes to mind or WordOccurrence or perhaps just Word. I have a feeling it'll save you pain in the long run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜