Rails下载空csv文件

时间:2014-02-12 09:42:08

标签: ruby-on-rails csv

我在使用rails应用程序下载csv文件时遇到问题。

首先控制器看起来像这样;

def report
  @report = SentMessage.where('user_id = ? AND created_at <= ? AND created_at >=   ?', current_user.id, params[:before], params[:after]).order('created_at Desc')
  respond_to do |format|
    format.html
    format.csv do
      response.headers["Content-Type"]        = "text/csv; charset=UTF-8; header=present"
      response.headers["Content-Disposition"] = "attachment; filename=sent_messages.csv"
    end
  end
end

然后我的report.csv.erb文件看起来像这样;

<%= provide(:title, "Sent Messages") %>
<div>
  <div class="panel radius"> <h2 class="text_center">Sent Messages</h2></div>
    <table class="table table-striped table-bordered table-hoverlarge-12 radius columns large-centered" id="sent_table">
      <thead>
        <tr>
          <th>To</th>
          <th>From</th>
          <th>Message</th>
          <th>Delivery Report</th>
          <th>cost</th>
          <th>Time</th>
        </tr>
      </thead>
      <tbody>
        <% @report.each do |message| %>
            <tr>
              <td><%= message.to %></td>
              <td><%= message.from %></td>
              <td><%= message.message %></td>
              <td><%= message.delivery %></td>
              <td><%= message.cost %></td>
              <td><%= message.created_at.to_datetime.strftime("%b %d, %Y %I:%M%P") %></td>
            </tr>
        <% end %>
      </tbody>
    </table>
  </div>
</div>

当我点击下载链接时,除了 report.csv.erb 文件中显示的标题之外,下载的文件只是空的。 可能是什么问题?

2 个答案:

答案 0 :(得分:0)

我只需要更改下载的链接;

  

<%= link_to "Download CSV", params.merge(format: "csv"), class: "button radius" %> 

它有效。

答案 1 :(得分:-1)

这样做可能对你有用。

def report
            @report = SentMessage.where('user_id = ? AND created_at <= ? AND created_at >=   ?', current_user.id, params[:before], params[:after]).order('created_at Desc')
                  respond_to do |format|
                           format.html
                           format.csv{
          response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present"
          response.headers["Content-Disposition"] = "attachment;                       filename=sent_messages.csv"}


                        end
  end