[英]Create mysql rows/columns
我写了一个红宝石脚本,将其自身连接到mysql数据库并创建了一个表(如果该表尚不存在)。 之后,脚本应将内容存储在此表中,我尝试使用以下方法存储此数据:
Table.create(:foo => "bar", :foobar => "something", :blallala => "blololl")
我也试过
Table.new(:foo => "bar", :foobar => "something", :blallala => "blololl")
但它似乎做同样的事情,因为我总是会收到错误:
Mysql :: Error:表'my-username.my-dbname'不存在:从表名显示完整字段
所以这就是我到目前为止所得到的:
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")
不起作用?
这为我工作:
# establish connection here
class Table < ActiveRecord::Base
self.table_name = "the_table"
end
unless Table.table_exists?
ActiveRecord::Schema.define do
create_table :the_table do |table|
table.column :foo, :string
table.column :bar, :string
table.column :blallala, :string
end
end
end
Table.create(:foo => "bar", :bar => "something", :blallala => "blololl")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.