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
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 Users.import(params[:file]) end
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