创建mysql行/列

时间:2012-05-05 13:14:58

标签: mysql ruby activerecord

我写了一个小的ruby脚本,它将自己连接到一个mysql数据库并创建一个表(如果这个表还没有存在)。在此之后,脚本应该在此表中存储内容,我尝试使用以下方法存储此数据:

Table.create(:foo => "bar", :foobar => "something", :blallala => "blololl") 

我也试过

Table.new(:foo => "bar", :foobar => "something", :blallala => "blololl") 

但似乎也是这样,因为我总是得到错误:

  

Mysql ::错误:表' 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")

所以问题是:我如何实际创建一个columo / row以及为什么Table.create(:foo => "bar", :foobar => "something", :blallala => "blololl")不起作用?

1 个答案:

答案 0 :(得分:1)

这对我有用:

# 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")