Rails exporting to CSV missing comma delimiter

408 views Asked by At

I am exporting a custom array to a csv file. Everything is exporting correctly, however it is not adding a comma delimiter between each instance. What am I missing in my code to add this separation?

data_services_controller

def export_all
 @list = DataService.all
  respond_to do |format|
  format.csv { render text: @list.to_csv }
end
end

data_service.rb

def self.to_csv
  CSV.generate do |csv|
    csv << ["Data Product", "Requestor"]
  all.each do |dp|
    csv << [dp.name ,dp.requestor]
  end
end
end

list.html.erb

<%= link_to "Export to CSV", export_all_data_services_path(:format => :csv), :class => "btn btn-primary" %>
2

There are 2 answers

0
smile2day On

@list.to_csv is calling the to_csv method on the relation returned by DataServive.all and not the class method you defined.

format.csv { render text: DataService.to_csv }

calls your to_csv class method. You won't need the @list instance variable.

0
Rokibul Hasan On

I have notice an wrong method calling in the controller, you can not call class method with an instance variable. You can rewrite the controller action as following and use send_data rather render text.

def export_all
    respond_to do |format|
     format.csv { send_data DataService.to_csv }
    end
end

And you already iterate all DataService in to_csv methods so I don't thing you need to query in export_all action. If you want to use @list any other purpose then you can use this.