2016-01-21 58 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