Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Importing and Exporting Records in CSV format in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 186
    Comment on it

    CSV files are comma separated values file that stores the data values in tabular format, where each column values are separated by commas. They are the lightest way of storing data in tabular format that is why most of the bulk data are exported and imported in this format. Rails also provides support for importing the data and exporting the data in csv format.

    All the csv operations in rails are performed by requiring the "csv" in the application. So you need to require it somewhere in application.rb or anyother place wherever you need to use it.

    require 'csv'


    Exporting Data in CSV format:

    For exporting data in csv format, here we are taking example of a product table that contains id, name and description. Suppose you want to export these 3 details of products in csv format. Then first we will create a class method in our model like this:

    class Product < ActiveRecord::Base
      def self.to_csv
          # Select the attributes that are needed in csv
          attribs = %w{id name description}
    
        # iterate over all the passed products and one by one create row of the csv
        CSV.generate(headers: true) do |csv|
          csv << attribs
          all.each do |product|
            csv << attribs.map{ |attr| product.send(attr) }
          end
        end
      end
    end

    Now you need to call the method in a controller or wherever you want to give the output in a csv file like this:

    class ProductsController < ApplicationController
      def index
        @products = Product.all
        respond_to do |format|
          format.html
          format.csv { send_data @products.to_csv, filename: "products.csv" }
        end
      end
    end

    Now whenever a request comes with type csv a products.csv file will get downloaded containing all the id,name,description of the products
     

    Importing Data from CSV:

    As exporting the csv fetches each row and writes each row in the csv format, similarly in case importing we need to read each line of the csv and create corresponding record. So there will 3 steps for this:

    a) Read the csv file
    b) Parse the file and create an array of records
    c) Iterate over the array and store the records into the table

    Thus in our case we can do this like:

    # Read the file
    file_content = File.read('file_path')
    
    # Parse the content, set headers true if csv contains headers
    csv = CSV.parse(file_content, :headers => true)
    
    # Iterate over csv and create records
    csv.each do |row|
      Product.create!(row.to_hash)
    end

    Thus we can import and export data in csv format.

    Hope you liked reading this.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: