2012-05-05 49 views
1

我寫了一個小的Ruby腳本,它本身連接到MySQL數據庫,並創建表(如果該表尚不存在)。在此之後,腳本應該存儲在該表中的內容我嘗試使用存儲這樣的數據:創建MySQL行/列

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

我也試過

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

但似乎做同樣的,因爲我總是得到錯誤:

Mysql::Error: Table 'my-username.my-dbname' doesn't exist: 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") 

所以,問題是:如何真正創建一個columo /行,爲什麼Table.create(:foo => "bar", :foobar => "something", :blallala => "blololl")不行?

+0

所以,這裏有什麼問題? –

+0

的問題是:如何真正創建一個columo /行?爲什麼'Table.create(:富=> 「欄」,:foobar的=> 「東西」,:blallala => 「blololl」)'不行? –

+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") 
+0

會嘗試和接受,如果它的工作原理;) –

+0

不是我沒有把它命名爲表... :( –

+0

調試你的代碼,那麼這個工作我的機器上 –