Import CSV File Into The Database In Rails Application.

Ruby on Rails



In this blog i’ll demonstrate how to import CSV file data into your rails application using Ruby’s built-in CSV library.It allow users to import records into the database by uploading a CSV file.

Below are steps to import the CSV records.

Add the following line in application.rb file

require 'csv'

Restart the server.

Add the block in your view page for users to upload CSV file.

<%= form_tag home_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import CSV" %>
<% end %>

Add the block in your controller

def import

Go to user model and write the following code block

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    Users.create! row.to_hash

But one thing to remember the column header names of your csv file must be match with the column names of the inserting table.when you reload the page and…

View original post 10 more words


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s