我写了一个小小的 ruby 脚本,它把自己连接到一个 mysql 数据库并创建一个表(如果这个表还不存在的话)。在此之后,脚本应将内容存储在此表中,我尝试使用以下方法存储此数据:
Table.create(:foo => "bar", :foobar => "something", :blallala => "blololl")
我也试过
Table.new(:foo => "bar", :foobar => "something", :blallala => "blololl")
但它似乎做同样的事情,因为我总是得到错误:
Mysql::Error: Table 'my-username.my-dbname' 不存在:SHOW FULL FIELDS FROM table-name
所以这就是我到目前为止得到的:
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "my-username",
:password => "my-password",
:database => "my-db-name",
:encoding => "UTF8"
)
table_name = "my_table"
unless ActiveRecord::Base.connection.tables.include? table_name
ActiveRecord::Schema.define do
create_table :"#{table_name}" do |table|
table.column :foo, :string
table.column :bar, :string
table.column :blallala, :string
end
end
end
class Table < ActiveRecord::Base
self.table_name = "#{table_name}"
end
Table.create(:foo => "bar", :foobar => "something", :blallala => "blololl")
#Table.new(:foo => "bar", :foobar => "something", :blallala => "blololl")
所以问题是:我如何实际创建一个列/行,为什么不起作用Table.create(:foo => "bar", :foobar => "something", :blallala => "blololl")
?