我有一些数据,我想让用户能够通过选择给定的日期范围来过滤这些数据。我可以通过使用我自己的过滤器在控制器中提供日期范围来操作数据:
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)
…但我希望用户能够选择一个开始日期和结束日期,并提交表单,以显示该日期范围的数据。我如何构建一个形式/函数做到这一点?
我已经在当前的应用程序中这样做了。这是表单视图。
<%
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