尝试创建过滤器选择以查找在给定日期范围内具有coursedates的计划:
AdminController:
def find_schedules
if params[:start_date] && params[:end_date]
start_date = params[:start_date]
end_date = params[:end_date]
@schedules = Schedule.find(:all, :conditions => {:coursedate => start_date..end_date})
redirect_to :action => 'find_results'
end
end
find_schedules视图:
<% form_tag(find_schedules_path) do %>
<%= select_date Date.today, :prefix => :start_date %>
<%= select_date Date.today, :prefix => :end_date %>>
<%= submit_tag "Submit", :disable_with => "Submitting..." %>
<% end %>
错误:
Processing AdminController#find_schedules (for ...) [POST]
Parameters: {"start_date"=>{"month"=>"3", "day"=>"23", "year"=>"2011"}, "commit"=>"Submit", "authenticity_token"=>"...", "end_date"=>{"month"=>"2", "day"=>"16", "year"=>"2012"}}
ArgumentError (bad value for range)
我似乎总是遇到日期/日期时间问题。 coursedate是日程表中的日期时间字段,如果这有任何区别。我只需要搜索日期,而不是时间。我是否需要以某种方式转换数据类型,因为mysql存储它的方式?或者......我还做错了什么?在此先感谢您的帮助。
在bdon的帮助下越来越近了,谢谢!现在我得到一个未定义的方法错误,但我应该能够解决这个问题:
ActionView::TemplateError (undefined method `each' for nil:NilClass) on line #26 of /admin/find_results.html.erb:
25: <tr class="<%= cycle('odd', 'even') %>">
26: <% @schedules.each do |schedule| %>
答案 0 :(得分:1)
您收到此错误是因为“范围”函数不支持哈希值,在这种情况下会传递哈希值:
1.9.3-p0 :008 > {:year => 2012, :month => 11, :day => 1}..{:year => 2012, :month => 12, :day => 1}
ArgumentError: bad value for range
相反,您需要将范围的开头和结尾设为DateTime对象:
1.9.3-p0 :010 > DateTime.new(2012,11,1)..DateTime.new(2012,12,1)
=> Thu, 01 Nov 2012 00:00:00 +0000..Sat, 01 Dec 2012 00:00:00 +0000
所以
start_params = params[:start_date]
start_date = DateTime.new(start_params["year"].to_i, start_params["month"].to_i, start_params["day"].to_i)
对end_date执行相同的操作。