Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export data to file CSV on Ruby Rails

Tags:

I'm trying export data using active record and csv class, but I dont have the file generated can help see me code.

when i click export does not open a dialog to download from csv am i missing something?

My Controller

def export_csv
    @contact = Contacts.find_by_sql("select * from contacts_list limit 10")
     respond_to do |format|
       format.html
       format.csv { send_data @contact.as_csv }
     end
  end

My Model

def self.to_csv
    attributes = %w{id name mail}

    CSV.generate(headers: true) do |csv|
      csv << attributes

      all.each do |contact|
        csv << attributes.map{ |attr| contact.send(attr) }
      end
    end
  end

My View

<%= link_to( 'Export CSV' ,{ :controller => :company, :action => :export_csv, format: "csv"}, { :class => "btn-ex" } ) %>

Console Ouput

Started GET "/company/export_cs" for 127.0.0.1 at 2019-12-17 11:31:26 -0200
Processing by CompanyController#export_cs as HTML

only this nothing more no errors no messages warnings.

like image 468
codevb Avatar asked Dec 17 '19 14:12

codevb


2 Answers

You need to generate the URL for the link in a different way - using URL helper, not controller/action params:

<%= link_to( 'Export CSV', companies_export_csv_path(format: "csv", { :class => "btn-ex" } ) %>

See also: Rails link_to :format => :xlsx not generating link to .xlsx path

like image 113
mrzasa Avatar answered Sep 28 '22 10:09

mrzasa


<%= link_to( 'Export' ,{ :controller => :company, :action => :export_csv, format: 'csv', :company_id => @company.id}, { :class => "btn-edit" } ) %>

Thanks Guys, workperfectly.

like image 28
codevb Avatar answered Sep 28 '22 10:09

codevb