Rails 4:使用视图中的表单过滤数据

时间:2016-09-08 17:30:22

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

我有一些数据,我想让用户通过选择给定的日期范围来过滤这些数据。我可以通过使用我自己的过滤器在控制器中提供日期范围来操作数据:

def self.filter_chart(date_start = 2.years.ago.to_s, date_end = Date.today.to_s)
    real_start = date_start.to_date
    real_end = date_end.to_date
    part_1 = PotentialClient.where('created_at >= ?', real_start)
    part_2 = part_1.where('created_at <= ?', real_end)

    return part_2
end

@clients = PotentialClient.filter_chart(2.days.ago.to_s, Date.today.to_s)

...但我希望用户能够选择开始日期和结束日期,并提交表单以显示该日期范围的数据。如何构建表单/函数来执行此操作?

1 个答案:

答案 0 :(得分:0)

我在我当前的应用中完成了这项工作。这是表单视图。

<%
  if params[:start_date].present? && params[:end_date].present?
    start_date = Date.parse(params[:start_date])
    end_date = Date.parse(params[:end_date])
  else
    start_date = Time.zone.today - 30.days
    end_date = Time.zone.today
  end
%>

<%= form_tag('', class: 'form', method: :post) do %>
  <input type="text" class="form-control datepicker" name="start_date" value="<%= start_date.strftime("%Y-%m-%d") %>">
  <input type="text" class="form-control datepicker" name="end_date" value="<%= end_date.strftime("%Y-%m-%d") %>">
  <input type="submit" class="btn btn-primary" value="Run report">
<% end %>

这是您的报告控制器。

def create
  if params[:start_date].present? && params[:end_date].present?
    start_date = Date.parse(params[:start_date])
    end_date = Date.parse(params[:end_date])
  else
    start_date = Time.zone.today - 30.days
    end_date = Time.zone.today
  end

  start_date = Time.zone.parse(params[:start_date]).beginning_of_day
  end_date = Time.zone.parse(params[:end_date]).end_of_day
  report_data = PotentialClient.where('created_at >= ?', start_date).where('created_at <= ?', end_date)
end