如何在Rails中为整个索引视图而不只是第一页使用send_data方法?

时间:2018-11-27 23:49:34

标签: ruby-on-rails ruby will-paginate

我希望能够以csv格式从“订单”表中下载索引数据。我已经可以使用以下代码实现此功能:

Type to mock must be an interface or an abstract or non-sealed class.

订单模型:

_table.Setup(x => x.DoSomething()).ReturnsAsync("My desired result");

但是,由于我有分页,这只能让我下载Order表中的前20个条目。我以为以下代码可以解决此问题,但它不会改变任何内容:

orders controller:

class OrdersController < ApplicationController
    before_action :find_order, only: [:edit, :destroy, :update, :show]

    def index
        @orders = Order.all.order("created_at DESC").paginate(:page => params[:page], :per_page => 20)
        # to allow csv and xls formats to be downloaded
        respond_to do |format|
            format.html 
            format.csv { send_data @orders.to_csv }
            format.xls { send_data @orders.to_csv(col_sep: "\t") } # tab separate to work with Excel
        end
    end

关于如何保留分页但能够下载Order表中的所有条目的任何想法?

1 个答案:

答案 0 :(得分:0)

我认为这可能就像将block_ctr = -1 block_data = [] with open(filename) as f: for line in f: if line: # test if line is not empty if line.startswith('@header'): block_ctr += 1 block_data.append([]) else: block_data[block_ctr].append(line.split()) 调用移到.paginate块中一样简单

format.html { ... }

MAY 必须在format.html块中添加class OrdersController < ApplicationController before_action :find_order, only: [:edit, :destroy, :update, :show] def index orders = Order.all.order("created_at DESC") # to allow csv and xls formats to be downloaded respond_to do |format| format.html do @orders = orders.paginate(:page => params[:page], :per_page => 20) end format.csv { send_data orders.to_csv } format.xls { send_data orders.to_csv(col_sep: "\t") } # tab separate to work with Excel end end ... end 。我目前无法测试此代码。