0

I am new to Ruby on Rails.

I want to write a module for uploading a CSV file in my application. Also, I want to import the data from that file to one of my tables in my Rails application.

In my application there is a model named "Book" which has four fields: name, author, publication_date and publisher_name.

I want to give user the ability to upload a CSV file with the format:

  • first column for name
  • second column for author
  • third for publication_date
  • fourth for publisher_name.

Also I want to add the validation so that upload will happen only when the file is of the expected format.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Joy
  • 4,197
  • 14
  • 61
  • 131

1 Answers1

0

You need a FasterCSV gem to do that.First install it and later in your model do like this:

    require 'csv'

       validates_format_of :book, :with => /^.+\.(csv)$/,
       :message => 'A .csv file is required.'

    records = CSV.foreach('yourpath/tocsvfile/filename.csv').map do |row|     
    Book.create!({
        :name              => row[0], 
        :author            => row[1], 
        :publication_date  => row[2], 
        :publisher_name    => row[3],
    })
end

For more information about CSV,you can find it here

Hope it Helps!

Pavan
  • 33,316
  • 7
  • 50
  • 76
  • Ruby comes with CSV in its standard library, so it's not necessary to load another gem. And, BTW, [that IS FasterCSV](http://stackoverflow.com/questions/5011395/what-is-ruby-1-9-standard-csv-library). – the Tin Man Feb 26 '14 at 06:49
  • Well ruby adopted the FasterCSV as its Standard CSV library see this SO top answer http://stackoverflow.com/questions/5011395/what-is-ruby-1-9-standard-csv-library – Pavan Feb 26 '14 at 07:01
  • @theTinMan Oops misjudged your comment.Apologies. – Pavan Feb 26 '14 at 07:10
  • I know. Feel free to remove both of yours if you want. – the Tin Man Feb 26 '14 at 07:11
  • @theTinMan That Wont be necessary.And BTW can you edit my answer as per your comments. – Pavan Feb 26 '14 at 07:14
  • I *can* edit it, but I won't because that would be changing the content of your answer. Changing formatting, and grammar is OK, but I won't change the meaning. – the Tin Man Feb 26 '14 at 07:16
  • @theTinMan OK,no problem :) – Pavan Feb 26 '14 at 07:18
  • @theTinMan I would like to know the feedback for my answer.Can you share. – Pavan Feb 26 '14 at 07:22