send_file之后的DoubleRenderError

时间:2014-01-23 13:00:08

标签: ruby-on-rails ruby ruby-on-rails-4

我在这段代码中遇到了一些奇怪的问题:

def export_csv
    user = User.find_by_u_token(params[:u])
    return render json: {status: 'error', descr: 'INVALID_U_TOKEN'} if !user
    return render json: {status: 'error', descr: 'INVALID_DELIMITER'} if !user.csv_del
    return render json: {status: 'error', descr: 'PARAMS_NOT_DEFINED'} if !params[:invoices]
    return render json: {status: 'error', descr: 'INVALID_USER_TYPE'} if !user.contractor? && !user.customer?

    invoices = invoices_for_user(user)
    pinvoices = params[:invoices].split(' ')

    return render json: {status: 'error', descr: 'INVALID_INVOICES'} if !check_invoices(invoices, pinvoices)

    export_invoices(pinvoices, user.csv_del)
    send_file("file.csv")

    return render json: {status: 'ok'}
end

我的export_invoices方法:

def export_invoices(pinvoices, delimiter)
    CSV.open("file.csv", "wb", {:col_sep => delimiter}) do |csv|
      Invoice.find(pinvoices).each do |i|
        csv << i.attributes.values
      end
    end
end

我有Render and/or redirect were called multiple times in this action.错误。 我试图评论一行send_file("file.csv"),一切正常。

问题出在哪里?

3 个答案:

答案 0 :(得分:1)

在上面的代码中删除行return render json: {status: 'ok'}并在此处创建模板export_csv.js.erb,然后编写成功代码

答案 1 :(得分:1)

基本上,您收到的错误消息告诉您,您只能拨打render一次。 send_file实际上正在进行渲染。当您到达代码中执行另一次渲染的最后一行时,您会收到错误。

问题是,您希望代码最终呈现什么?是CSV文件还是json响应?你不能兼得。很明显,您想要删除返回json响应的行。

答案 2 :(得分:0)

尝试删除

return render json: {status: 'ok'}

它会起作用的原因:   因为send_file本身会渲染,所以再次这样做没有任何意义。