Search code examples
databaseruby-on-rails-3fill

Fast solution to fill create and fill db table with data from csv file


Like in title.. I want to create table in my db and then fill it with records from my csv(tab is ";") file. There records (and whole table) won't be updating or changing by anyone. I just have to create db(only Postgres) with these records. I want later take randomly from this table some records. Any tips? Or maybe taking random records directly from csv file instad from db is better solution? Plz help


Solution

  • You can make a command line tool that reads your cvs file and use ActiveModel to talk to the database. In this case you create your Model and Database as you would do in any other rails Application.

    To read your cvs file you culd do this:

    require 'csv'
    
    CSV.foreach(fileName, :headers => true, encoding: "UTF-8") do |row|
      row['myfiled'].to_s
    end
    

    You need the csv gem and you have to replace myfield with the name of the column you want to use. If you have the data in ruby you create your models as if you would to in rails. Put the definitions in the same file or use require to reference your models.

    Alternatively you could just read the cvs file and randomly decide if you want to use the data. In this case you do not need to put it in the database.