0

我有一个名为 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") %>

activerecord 过滤器大概是这样的:

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

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

4

1 回答 1

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

这样,您可以从参数中捕获日期并以您想要的方式对其进行格式化并将其放置在您的查询中。

于 2013-07-03T16:15:50.713 回答