使用表单提交在PDF导出期间选择月份。

时间:2013-07-03 15:54:55

标签: ruby-on-rails-3 date activerecord

我有一个名为Mileages的Rails 3.2应用程序。我使用Prawn PDF添加了里程数索引操作的PDF输出。

mileages_controller的索引操作如下所示:

def index
    @mileages = Mileage.find_all_by_user_id(current_user.id)
    @mileages_months = Mileage.find_all_by_user_id(current_user.id).group_by { |t| t.created_at.beginning_of_month }


    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @mileages }
      format.pdf do
            pdf = MileagePdf.new(@mileages, view_context)
            send_data pdf.render, filename: "mileages_report.pdf",
                                  type: "application/pdf",
                                  disposition: "inline"
          end
    end
  end

我想要做的是,在PDF版本的索引视图上有一个链接,但旁边将是开始日期和结束日期。然后,PDF将仅显示这两个日期之间的里程条目。

PDF链接只是<%= link_to "Mileage Report (PDF)", mileages_path(@mileages, format: "pdf") %>

主动记录过滤器可能是这样的:

@mileages = Milage.where(:date => ??..??)

我不确定如何将上述内容与日期输入联系起来。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

尝试提交某种表单,因为您有日期。

 <%= form_tag(mileages_path(format: :pdf), method: :get) do -%>
    <%= date_select("mileage_start", "date",  order: [:year,:month,:day])%>
    <%= date_select("mileage_end", "date",  order: [:year,:month,:day])%>
    <%= submit_tag %>
  <%end%>

<强> UPDATED with Final answer from chat

  def index 
    start_date = params[:mileage_start] 
    end_date = params[:mileage_end] 
    if start_date && end_date 
      dates = get_start_and_end_date(start_date,end_date) 
      @mileages_pdf = Mileage.where(date: dates[:start_date]..dates[:end_date]) 
   end 

    respond_to do |format|
     # format.html # index.html.erb
     # format.json { render json: @mileages }
      format.pdf do
        pdf = MileagePdf.new(@mileages_pdf, view_context)
        send_data pdf.render, filename: "mileages_report.pdf",
        type: "application/pdf",
        disposition: "inline"
      end
    end   
  end 

  def get_start_and_end_date(start_date,end_date) 
    hsh = {} 
    hsh[:start_date] = build_date(start_date)
    hsh[:end_date] = build_date(end_date)
    hsh 
  end

  def build_date(hsh)
    DateTime.new(hsh["date(1i)"].to_i,hsh["date(2i)"].to_i,hsh["date(3i)"].to_i)
  end

通过这种方式,您可以从params中捕获日期并按照您希望的方式对其进行格式化,并将其放入查询中。