简体   繁体   中英

Rails - Filter by date range

Attempting to create a filter select to find schedules with coursedates within a given date range:

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 view:

<% 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 %>

Error:

    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)

I always seem to have trouble with date/datetime stuff. coursedate is a datetime field in the schedules table, if that makes any difference. I only need to search for dates, not times. Do I need to transform the data type somehow because of how mysql stores it? Or... what else am I doing wrong? Thanks in advance for your help.

Getting much closer after bdon's help, thank you! Now I'm getting an undefined method error, but I should be able to figure that out:

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| %>

You're getting this error because the "range" function doesn't support hashes, which are being passed in this case:

1.9.3-p0 :008 > {:year => 2012, :month => 11, :day => 1}..{:year => 2012, :month => 12, :day => 1}
ArgumentError: bad value for range

Instead you need to make the start and end of the range be DateTime objects:

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 

So

start_params = params[:start_date]
start_date = DateTime.new(start_params["year"].to_i, start_params["month"].to_i, start_params["day"].to_i)

Do the same for end_date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM