Save data to a csv file

0

I need to save my data from the Rails database in a CSV file.

I followed the steps in this post: link

But when you do everything as you put it there, when opening in the browser I see this error:

500 Internal Server Error
If you are the administrator of this website, then please read this web application's
log file and/or the web server's log file to find out what went wrong.

This would be my code:

The index , of my controller Terminal :

def index
  @terminals = Terminal.all

  @terminals = Terminal.order(:name)
  respond_to do |format|
    format.html
    format.csv {render text: @terminals.to_csv}
  end
end

The Terminal model, with its CSV function:

def self.to_csv
  CSV.generate do |csv|
    csv << column_names

    all.each do |terminal|
      csv << terminal.validates.values_at(*column_names)
    end
  end
end

And this would be the view index :

 <% title "Enable Terminals" %>
 <p id="notice"><%= notice %></p>

 <h1><%= yield(:title) %></h1>
 <div class="menu">
 <!-- < link_to "Upload terminal list", upload_path> -->
 </div>
 <%= render partial: "terminal", collection: @terminals %>

Would something in the view be missing?

    
asked by Iker 17.05.2017 в 12:00
source

1 answer

0

Check that you have added the CSV library correctly and do not forget to restart your application (that is, from the command line, canceling the current process and running the rails server command again).

Also, you have an error here:

all.each do |terminal|
  csv << terminal.validates.values_at(*column_names)
end

Instead of validates , you should have attributes :

all.each do |terminal|
  csv << terminal.attributes.values_at(*column_names)
end

Not related to your error, but relevant: You could omit the line @terminals = Terminal.all completely, as you replace its content one line below.

This would be your method index :

def index
  @terminals = Terminal.order(:name)

  respond_to do |format|
    format.html
    format.csv {render text: @terminals.to_csv}
  end
end
    
answered by 17.05.2017 в 14:40