Rails将csv导入模型中的数据库

时间:2016-08-10 10:05:10

标签: ruby-on-rails database postgresql csv

我是新的rails用户,我需要堆栈帮助!

我搜索在我的数据库中加载一些csv文件,我正在使用postgres。为此,我在模型

中获得了此方法
class Station < ApplicationRecord
  def self.import_from_csv()
    CSV.foreach('resources/locations.csv', headers: true) do|row|                                                                 
      station = Station.new(
        id: row[0].to_i,
        name: row['Name'],
        city: row['City'],
        default_dest: row['Default dest'],
        public: row['Public'] == 'true',
        lat: row['Lat'].to_f,
        long: row['Long'].to_f
      ).save!
    end
  end
end    

这在我的控制器

def index
  respond_to do |format|
    format.html {
      @stations = Station.all
      render
    }
    format.json {
      @total = Commute.count
      @commutes = Commute.filter(params)
      render
    }
  end
end

这在我的 schema.rb

create_table "stations", force: :cascade do |t|
  t.string   "name",         null: false
  t.string   "city",         null: false
  t.float    "lat",          null: false
  t.float    "long",         null: false
  t.boolean  "public",       null: false
  t.string   "default_dest"
  t.datetime "created_at",   null: false
  t.datetime "updated_at",   null: false
end

但我的数据库中没有数据加载...

也许有人知道是否有一个rake commande我必须运行或类似的东西?

1 个答案:

答案 0 :(得分:0)

您可以通过这种方式继续推断,我会将Station.new(...).save!替换为Station.create!(...)

您很快就会面临时间问题。如果您要导入许多记录,那么您需要花费很长时间。请使用http://www.sqlservercentral.com/Forums/Topic537592-338-1.aspx gem并执行此操作:

class Station < ApplicationRecord

  def self.import_from_csv
    stations = CSV.foreach('resources/locations.csv', headers: true).map do |row|                                                                 
      Station.new(
        id: row[0].to_i,
        name: row['Name'],
        city: row['City'],
        default_dest: row['Default dest'],
        public: row['Public'] == 'true',
        lat: row['Lat'].to_f,
        long: row['Long'].to_f
      )
    end
    Station.import(stations)
  end
end