Ruby on Rails

How to import CSV files in Ruby on Rails

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 name and 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[0]
            company_hash.code = row[1]
            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!

Happy coding!

 

Sample CSV countries

Fool Dev

I didn't get trained by the school system like other kids, and when I did concentrate on learning, my mind was cluttered and locked by the programming of the system. © Huey Newton