2016-01-21 57 views
0

我有一個很大的CSV文件,我想填充一個模型,一旦列填充CSV就不會改變。我也有我認爲會採用CSV並將其添加到數據庫模型的方法。我不確定在哪裏放置該方法以及如何調用它?在哪裏添加代碼CSV到模型軌道

目前我在我的Rails應用程序中的.rb文件中有方法,我從終端調用它。但我收到以下錯誤:

ruby postcode.rb 
postcode.rb:6:in `block in <main>': uninitialized constant Place (NameError) 
    from postcode.rb:5:in `each' 
    from postcode.rb:5:in `<main>' 
Method/.rb file: 

這是我解析CSV並將數組中的每個數組添加到'Place'模型的方法。

require 'csv' 

csv_text = File.read('GB_full.csv') 
csv = CSV.parse(csv_text, :headers => false) 
csv.each do |row| 
Place.create!(row.to_hash) 
end 

型號:

class CreatePlaces < ActiveRecord::Migration 
    def change 
    create_table :places do |t| 
     t.string :country_code 
     t.string :postal_code 
     t.string :place_name 
     t.string :admin_name_1 
     t.string :admin_code_1 
     t.string :admin_name_2 
     t.string :admin_code_2 
     t.string :admin_name_3 
     t.string :admin_code_3 
     t.string :latitude 
     t.string :longitude 
     t.string :accuracy 

     t.timestamps null: false 
    end 
    end 
end 

回答

1

我把這個遷移。如果您認爲您可能希望在某個時候再次執行該操作,那麼將大部分代碼作爲類方法(需要csv文件名)放入模型中,然後從遷移中調用它。

+0

謝謝@MaxWilliams,但我不知道該怎麼做。 – Stoob

+1

然後看! –

1

我想補充的方法到Place模型首先,你可以經過重構出來,當/如果你的模型變得臃腫

require 'csv' 

class Place < ActiveRecord::Base 
    def self.import_from_csv(text) 
    CSV.parse(text, :headers => false).each do |row| 
     create!(row.to_hash) 
    end 
    end 
end 

,並調用它像這樣:

csv_text = File.read('GB_full.csv') 
Place.import_from_csv(csv_text) 
+0

我是從軌道控制檯運行的嗎? – Stoob

+1

是的,如果你的文件在rails根目錄下。如果不是隻指定文件的完整路徑。而且您需要將上述方法添加到您的模型中 – ssuljic