Rails - Export CSV not working as expected (undefined method) - ruby-on-rails

I am doing a CSV Export in Rails App.
The data is returned as a JSON array from the backend API.
But now I am getting error as "undefined method 'to_csv' for #Hash:0x007f149a5ff978" in the export_data method.
I have included require "csv" in the config/application.rb file, and did server restarts.
Not sure what I am doing wrong.
index.html.erb
<button class="btn btn-default">Export to CSV</button>
usage_controller(front end)
def export_data
rest_resource = RestClient::Resource.new( ENV['USAGE_METRICS_API'] + '/get_events_data', :verify_ssl => false )
request = rest_resource.get :Authorization => cookies.signed[:remember_token], :content_type => 'application/json'
#events_data = JSON.parse(request)
respond_to do |format|
format.html
format.csv { send_data #events_data.to_csv }
end
end
def self.to_csv
CSV.generate do |csv|
csv << column_names
all.each do |event|
csv << event.attributes.values_at(*column_names)
end
end
end

Your self.to_csv method doesn't make sense in the controller
You need to move to_csv to you model which will serialize the data into a csv
follow this tutorial to implement this: http://railscasts.com/episodes/362-exporting-csv-and-excel

Related

Rails' export csv function "undefined method `export' for nil:NilClass"

I'm making an export to csv file functionality in a Ruby on Rails repo and I'm almost done. However, when I press the "Export all" button, I get the undefined method `export' for nil:NilClass error. The log shows that format.csv { send_data #foos.export, filename: "foos-#{Date.today}.csv" } went wrong. What am I missing please?
This is model
class Foo < ApplicationRecord
has_many :bars
def export
[id, name, foos.map(&:name).join(' ')]
end
end
This is part of controller
def index
#foos = Foo.all
end
def export
all = Foo.all
attributes = %w{name}
CSV.generate(headers: true) do |csv|
csv << attributes
all.each do |foo|
csv << attributes.map{ |attr| foo.send(attr) }
end
respond_to do |format|
format.csv { send_data #foos.export, filename: "foos-#{Date.today}.csv" }
end
end
end
def name
"#{foo_id} #{name}"
end
This is View
<button class="btn btn-success">export all</button>
This is Routes
Rails.application.routes.draw do
resources :foos
get :export, controller: :foos
root "foos#index"
end
This is Rake (lib/tasks/export.rb)
namespace :export do
task foo: :environment do
file_name = 'exported_foo.csv'
csv_data = Foo.to_csv
File.write(file_name, csv_data)
end
end
Start by creating a service object that takes a collection of records and returns CSV so that you can test the CSV generation in isolation:
# app/services/foo_export_service.rb
# Just a Plain Old Ruby Object that converts a collection of foos into CSV
class FooExportService
# The initializer gives us a good place to setup our service
# #param [Enumerable] foo - an array or collection of records
def initialize(foos)
#headers = %w{name} # the attributes you want to use
#foos = foos
end
# performs the actual work
# #return [String]
def perform
CSV.generate do |csv|
#foos.each do |foo|
csv << foo.serializable_hash.slice(#headers).values
end
end
end
# A convenient factory method which makes stubbing the
# service easier
# #param [Enumerable] foos - an array or collection of records
# #return [String]
def self.perform(foos)
new(foos).perform
end
end
# example usage
FooExportService.perform(Foo.all)
Not everything in a Rails application needs to be jammed into a model, view or controller. They already have enough responsiblities. This also lets you resuse the code for example in your rake task if you actually need it.
This simply iterates over the collection and uses Rails built in serialization features to turn the model instances into hashes that can be serialized as CSV. It also uses the fact that Hash#slice also reorders the hash keys.
In your controller you then just use the service object:
class FoosController
def export
#foos = Foo.all
respond_to do |format|
format.csv do
send_data FooExportService.perform(#foos),
filename: "foos-#{Date.today}.csv"
end
end
end
end
You don't even really need a separate export action in the first place. Just use MimeResponds to add CSV as an availble response format to the index:
class FoosController
def index
# GET /foos
# GET /foos.csv
#foos = Foo.all
respond_to do |format|
format.html
format.csv do
send_data FooExportService.perform(#foos),
filename: "foos-#{Date.today}.csv"
end
end
end
end
<%= link_to("Export as CSV", foos_path(format: :csv)) %>

How to create a file on users machine instead of creating in server and then to download using rails

I am working on to allow download an excel file with the below code:
login = Etc.getlogin
#dataFile = "C:/rails/#{login}data.csv"
csv1=CSV.open(#dataFile, 'w') do |csv|
$data.each do |eachrow|
csv << [eachrow.name+"#gmail.com"]
end
end
send_file(#dataFile, :filename => "#{login}data", :type => "application/csv")
Using the above code, I am able to create a file and write the data.
Instead of this, how do i write the data in csv and get downloaded into users machine instead of saving in local/server.
What you can do is generate a string with the CSV library, using CSV::generate instead of CSV::open.
Controller:
class DataController < ApplicationController
def download
respond_to do |format|
format.csv { send_csv_download }
end
end
private
def send_csv_download
string = CSV.generate do |csv|
#data.each { |row| csv << ["#{row.name}#gmail.com"] }
end
send_data string, filename: 'foo.csv', type: :csv
end
end
config/routes.rb:
get '/download', to: 'data#download'
View:
<%= link_to 'Download CSV', download_path(format: :csv) %>
Note: Obviously, I have no idea where you get your #data from, since it isn't specified in your question.

rails export csv return empty in production which works fine locally

I tried to export a csv file in my Rails app.
It works fine locally and if will return a csv file with data. However when push to production, it return a csv file which is empty.
Is there any possible reason about this problem?
View:
<%= link_to "Export Places", {controller: "admin/neighborhoods", action: "export_csv", format: "csv"}, 'data-no-turbolink' => true, :class => "button" %>
Route:
get 'admin_neighborhoods_export' => 'admin/neighborhoods#export_csv'
Controller:
def export_csv
#neighborhoods = Neighborhood.order(:created_at)
time = Time.now.strftime("%Y%m%d%H%M%S").to_s
respond_to do |format|
format.html
format.csv do
headers['Content-Disposition'] = "attachment; filename=\"places_export_#{time}.csv\""
headers['Content-Type'] ||= 'text/csv'
send_data(Neighborhood.to_csv(#neighborhoods), :type => "text/csv", :filename => "places_export_#{time}.csv")
end
end
end
Modal:
def self.to_csv(neighborhoods)
CSV.generate(headers: true) do |csv|
nbh_columns = []
nbh_columns.concat(column_names)
nbh_columns.concat(["maponics_neighborhood", "maponics_city", "maponics_state"])
csv << nbh_columns
neighborhoods.each do |neighborhood|
values = []
values.concat(neighborhood.attributes.values_at(*column_names))
if neighborhood.gid.present?
nbh_maponic = NeighborhoodBoundariesMaponics.find(neighborhood.gid)
values.concat([nbh_maponic.neighborhd, nbh_maponic.city, nbh_maponic.state])
else
values.concat(["", "", ""])
end
csv << values
end
end
end
Have found the reason.
There is a bad data in production db. So one error happens when I use 'find' to search a row in db.
NeighborhoodBoundariesMaponics.find(neighborhood.gid)
Now I change to use 'where' and it works.

How to generate a CSV file in action?

I am trying to generate a CSV output with data from my database. I would like to provide these data to a third party, so I picture I would give to someone a URL (website.com/api_data/cars) and by accessing this URL the person would be able to work with it - I think I want to access the URL and then to see there (in the action) data displayed and separated by , or ;.
But how to do that?
So far, I am trying following approach:
csv_string = CSV.generate do |csv|
cols = ["column one", "column two", "column three"]
csv << cols
csv << ["A", "B", "C"]
#filename = "data-#{Time.now.to_date.to_s}.csv"
end
send_data(csv_string, :type => 'text/csv; charset=utf-8; header=present', :filename => #filename)
This is in the controller generate_data and action csv_cars.
When I run this action (webste.com/generate_data/csv_cars), it will automatically pop up a window to download the file.
But how to write the CSV content to the action? So when I open the URL, I'll see there written the content from the database?
I know this is an old thread but I came across it in my search so in case someone else does the same, here's my answer and what worked for me.
I think bhanu had a good way of going about it but I did change something. Instead of doing #cars within the respond_to, I just called send_data Cars.to_csv since, as Rob stated, it was made as a class method. It worked beautifully for me.
class Car < ActiveRecord::Base
def self.to_csv(make)
attributes = %w{id name price} #customize columns here
cars = Car.where(maker_name: make)
CSV.generate(headers: true) do |csv|
csv << attributes
cars.each do |car|
csv << attributes.map{ |attr| car.send(attr) }
end
end
end
end
And then in the controller
class CarsController < ApplicationController
def index
send_data Cars.to_csv('Chevy'), filename: "cars-#{Date.today}.csv"
end
end
I understand that this will be called when you go to cars/index but you can put that into any method, if statement or anything you want and just have it called whenever you would like from there. You can also have arguments, as I did above with make, and query for certain fields. It was definitely a lot easier than I thought it was going to be. Hope this helped someone.
You need to do something like this.
def csv_cars
headers = ['column one', 'column two', 'column three']
csv_data = CSV.generate(headers: true) do |csv|
csv << headers
csv << ["A", "B", "C"]
end
send_data csv_data, filename: "data-#{Date.today.to_s}.csv", disposition: :attachment
end
define a to_csv method in your model as shown below
class Car < ActiveRecord::Base
def self.to_csv
attributes = %w{id name price} #customize columns here
CSV.generate(headers: true) do |csv|
csv << attributes
all.each do |car|
csv << attributes.map{ |attr| car.send(attr) }
end
end
end
end
Later in your controller
class CarsController < ApplicationController
def index
#cars = Car.all
respond_to do |format|
format.html
format.csv { send_data #cars.to_csv, filename: "cars-#{Date.today}.csv" }
end
end
end

rails csv generator not reaching the model

I have in my controller a section that generates an array of Song objects. For each song object, I want to output some of it's information to a csv file. I found instructions online and followed them to the best of my ability.
The controller:
def index
#stations = Station.all
#csv crap
#played = []
Station.first.users.each do |u|
u.playlists.where("updated_at > ?", Date.today).each do |p|
#played << p
end
end
#songs = []
if !#played.empty?
#played.each do |pl|
pl.songs.each do |s|
#songs << s
end
end
end
#data = []
#data << "Song"
#data << "Album"
#data << "Artist"
(0...#songs.length).each do |s|
son = #songs[s]
#data << [son.title, Album.find(son.album_id).name, Artist.find(son.artist_id).name]
end
respond_to do |format|
puts "******************\n\n\n\n\n\n\n\n"
puts #songs.inspect
puts "******************\n\n\n\n\n\n\n\n"
format.html
format.csv { send_data #data.to_csv(), filename:"daily_report.csv" }
end
end
The model:
def self.to_csv(options = {})
puts "fuck all"
CSV.generate(options) do |csv|
csv << column_names
options.each do |item|
csv << item.title
csv << item.attributes.values_at(*column_names)
csv << item.attributes.values_at(*column_names)
end
end
end
For some reason, the controller is never using the model to generate the csv, which it should be. I have to extra stuff in the controller to try to make it generate correctly there, but I really want it to generate in the model. Any idea why it never hits the self.to_csv in the model?
Your model's to_csv method isn't being called because you're not calling it - you're calling a to_csv instance method on an array.
You need something along the lines of
ModelClass.to_csv(#songs)
and your to_csv method should be closer to
def self.to_csv(data, options = {})
CSV.generate(options) do |csv|
csv << column_names
data.each do |item|
csv << [item.title]
csv << item.attributes.values_at(*column_names)
csv << item.attributes.values_at(*column_names)
end
end
end
I'm a bit confused about what you're adding to the csv (for example why are the item attributes added twice?) but this should at least produce a csv.

Resources