Search code examples
ruby-on-railsruby-on-rails-3csvruby-on-rails-3.1

Best option for a CSV upload in rails?


What's the best option to create a form whereby you can upload a CSV file and choose a model e.g. (User, Company, Contact) which takes the contents of the CSV file and inserts them line by line into the database skipping any duplicates but conforming to the validations in the model?


Solution

  • I think there are two parts to your question:

    1. Uploading the file
    2. Parsing the CSV into your table.

    For uploading the file I like Carrierwave, but Paperclip is also very popular. I would upload the file first and store it somewhere so that you can then do the parse in a DelayedJob (or other asynchronous process). Once the file is stored, you can kick off the job to parse it and store it in your table, using the built in CSV parser for Ruby should do well for this task (it used to be called FasterCSV).

    The code to parse it is something like:

    parsed_file = CSV.parse(imported_file, :headers => true, :skip_blanks => true)
    

    You can then iterate through each "object" in the parse_file and handle it as needed.