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:
name
author
publication_date
publisher_name
. Also I want to add the validation so that upload will happen only when the file is of the expected format.
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.