Today we are going to learn how to upload data from a CSV file. We can imagine countries like we have CSV file where exist all countries or some of the countries then how to import these into our database “countries” table.
At first in the model, as like
country.rb and we have two columns for a country which is
code see the below
class Country < ApplicationRecord # Bulk upload companies def self.import(file) CSV.foreach(file.path, headers: true) do |row| company_hash = Country.new company_hash.name = row company_hash.code = row company_hash.save end end end
now we can add some functionalities in our countries controller
class CountriesController < ApplicationController def new @country = Country.new end def create Country.import(params[:country][:file] flash[:notice] = "Countries uploaded successfully" redirect_to countries_path #=> or where you want end end
now final touch in our new.html.erb I mean CSV upload form
<%= form_for @country, url: countries_path do |f| %> <div class="form-group"> <%= f.label :file, "Upload CSV File" %> <%= f.file_field :file, class: 'form-control-file', required: true %> </div> <%= f.button :submit, "Upload CSV", class: 'btn btn-primary' %> <% end %>
here we go!
Sample CSV countries