生成具有csv格式的表格 [英] Generate form for with csv format

查看:221
本文介绍了生成具有csv格式的表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Form来指定两个日期字段,该字段指定了要放入CSV文件中的数据的时间跨度.我能够创建我的csv文件,但无法获得响应的csv格式.

I am trying to use form for to specify two date fields, which specifies a timespan for data that I want to put inside a CSV file. I am able to create my csv file but I cant get rails to respond to csv format.

在这里,我在form_for字段中添加了格式::csv,但它不会在我的控制器中响应该格式.

Here I have added my format: :csv in the form_for field, but it wont respond to that format in my controller.

<%= form_for(:estimation, html: {class: "estimations-form-horizontal"}, url: research_path, format: :csv, method: :get) do |f| %>

  <div class="form-group-estimations">
    <%= f.label :from_start_date, "Från och med" %>
    <%= f.date_field :from_start_date, class: "form-control" %>
  </div>

  <div class="form-group-estimations">
    <%= f.label :to_end_date, "Till och med" %>
    <%= f.date_field :to_end_date, class: "form-control" %>
  </div>

  <%= f.submit "Hämta data", class: "btn btn-primary" %>
<% end %>

我的控制器,使用format.csv ...

My controller, using format.csv ...

  def research
    if (params[:estimation] && params[:estimation][:from_start_date] && params[:estimation][:to_end_date])
      start_date = params[:estimation][:from_start_date].to_date.beginning_of_day
      end_date = params[:estimation][:to_end_date].to_date.end_of_day
      if(start_date > end_date)
        puts "Dates are in wrong order"
      else
        @estimations = Estimation.where(:created_at => start_date..end_date)
        puts to_csv(@estimations)

        respond_to do |format|
          format.csv { send_data to_csv(@estimations), filename: "skattningar-#{Date.today}.csv" }
        end

      end
    else
      puts "Not enough data"
    end
  end

推荐答案

:url与:format冲突如果同时传递:url和:format, 网址会覆盖格式的使用,因此您需要在网址中传递格式 像这样:

:url conflicts with :format If you are passing both :url and :format, url overwrites the use of format, so you’ll need to pass it in the url like so:

form_for user, :url => user_path(@user, :format => :json)

这篇关于生成具有csv格式的表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆