何处将代码CSV添加到模型轨道

时间:2016-01-21 11:39:51

标签: ruby-on-rails ruby 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并将数组中的每个数组添加到&#39; Place&#39;的方法。模型。

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

2 个答案:

答案 0 :(得分:1)

我会把它放在迁移中。如果您认为您可能希望在某个时刻再次执行此操作,那么将大部分代码作为类方法(采用csv文件名)放在模型中,然后从迁移中调用它。

答案 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)
相关问题