How to import CSV files in Ruby on Rails via JavaScript with UseCSV
How to import CSV files in Ruby on Rails with UseCSV
UseCSV makes it easy to import CSV files into your Rails application, so you can focus on developing your app, not reinventing the wheel.
#What is UseCSV?
UseCSV is an all-in-one CSV import product that gives you a delightful CSV importer experience for your users. All you have to do is drop-in the UseCSV JS library, and create a webhook endpoint to receive uploads. This takes away all the headaches of building CSV import functionality in-house .
Here's a sneak peak of what the import experience will be for your users (this opens in a modal inside your app):
Here are just a few of the awesome features of UseCSV:
- Frontend libraries which add the UseCSV import button and modal to your app
- Receive imported data as a webhook or callback
- Automatic smart column matching
- Supports CSV and all Excel formats (xlsx, xls, xlt), including legacy Excel versions
- Handles large import files
- Includes a library of common validation rules to choose from
Without further ado, let's get started!
#Setup your UseCSV account
You'll want to first grab a free UseCSV developer account. Once you've signed up and logged in, you'll see an Importer called "My First Importer" which has already been created for you.
Click the View button. Here you can configure your Importer. Note the Key and Webhook URL fields, we'll need these later on.
Head down to the Column section, where you can setup the data model for this Importer.
Click Add Column to create a new column, for example you could add a first_name column to begin with. Create as many columns as you like.
Add CSV import to your JavaScript Rails app
Generating your Rails app
If you don't have an existing Rails app, create a new Rails app using the following command:
rails new myapp
cd myapp
Including the UseCSV frontend JS library using importmap
Including the UseCSV JS library into your Rails front end is just like importing any JS lib. If you're using importmap-rails, simply run:
bin/importmap pin @usecsv/js
Then, import the package into application.js and add our helper function (you may be using jQuery or similar here instead of the onclick):
import useCsvPlugin from "@usecsv/js" function importData(){ useCsvPlugin({ importerKey: "your-importer-key", user: { userId: "12345" }, metadata: { anotherId: "1" }, }); } window.importData = importData
Now you can add UseCSV button for the modal popup in your view:
<button type="button" id="import-data-button" onclick="importData()"> Import Data </button>
Including the UseCSV frontend JS library using a script tag
Alternatively if you don't want to use importmap you can simply use a script tag (see the docs. In your <head> add:
<script src="https://unpkg.com/@usecsv/js/build/index.umd.js"></script>
Then you can create an onclick importData() helper function like below, using whichever frontend framework you're using. There's an example in our docs.
Creating a controller in Rails to receive webhook
Now create a controller to receive the UserCSV webhook. In your routes file (config/routes.rb), add a route for the webhook endpoint:
post '/webhook/import' => 'webhook#import'
Next, create the webhook controller (app/controllers/webhook_controller.rb)
:
class WebhookController < ApplicationController skip_before_action :verify_authenticity_token def import webhook_data = JSON.parse(request.body.read) # do something with webhook_data logger.info webhook_data respond_to do |format| format.json { } end end end
This action will parse the JSON from the request body and store it in the webhook_data variable. You can then do whatever you want with that data, such as save it to a database or process it in some way.
To connect this webhook endpoint up with your UseCSV importer, you can use a free Cloudflare tunnel
Launch the Cloudflare tunnel:
cloudflared tunnel localhost:3000
Copy the tunnel url cloudflared generates, then append on your new webhook endpoint path /webhook/import
and paste the complete Webhook URL into the UseCSV admin to finish connecting everything up.
We're ready to try your first import
Make sure your Rails app is running. Go to http://localhost:3000
click on Import Data
to open the importer modal.
Upload your CSV file, match the columns and then click import.
Watch your Rails console log for the webhook payload. UseCSV will automatically split up the webhooks into batches of 1,000 rows.
Where to from here?
UseCSV makes it simple to add delightful CSV import to your app. There are many powerful features under the hood including themes and validation rules. Checkout the docs for more info.