Export CSV Rails


1) make some file on project root directory named abc.csv
2) If Permision Denied error occurs then run this command

chmod 777 abc.csv

3) Rake task

namespace :export do
task :csv => :environment do
    require 'csv'
    CSV.open("abc.csv", "w") do |csv|
      @cities = City.joins(:hotels).uniq # your query here
      csv << ['city_id', 'city_name']  #column head of csv file
      @cities.each do |city|
      csv << [city.id, city.name] #fields name
      end
    end
  end
end

4) In project repository root run this command:

rake export:csv
Advertisements

I am Senior Software Engineer. I love reading, writing, sharing,developing, hiking, movies, trips, mountains, brooks, hills etc.

Tagged with: , ,
Posted in Ruby Little Codes
2 comments on “Export CSV Rails
  1. I think its import not export. And for importing CSV or XLS here is very good railscast tutorial
    http://railscasts.com/episodes/396-importing-csv-and-excel

  2. taimoor.changaiz says:

    Nope the above code is for Exporting CSV

    Export = creating CSV
    Import = Grabbing CSV

    and tutorial you provided is for importing by browser in rails application not for script.

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

StackOverFlow
Categories
Archives
%d bloggers like this: