我有一個很大的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
謝謝@MaxWilliams,但我不知道該怎麼做。 – Stoob
然後看! –