Leave a comment

Import CSV File Into The Database In Rails Application.


Ruby on Rails

CSV

 

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.

Step:1
Add the following line in application.rb file

require 'csv'

Restart the server.

Step:2
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 %>

Step:3
Add the block in your controller

def import
   Users.import(params[:file])
  end

Step:4
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
  end
end

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: