views:

489

answers:

2

I need to take in a Date Range from the UI, retrieve the records within that range and plot a graph. This is the relevant section in my Rails view.

<span>
    <%= check_box_tag :applyRange, @params[:applyRange]%>
    From
    <%= select_date Time.now, :prefix=>"fromDate"  %>
    To
    <%= select_date Time.now, :prefix=>"toDate" %>
</span>

Back on the controller/action side, this is what I had to do to reconstruct the date values back (hack hack puts hack puts hack...)

fromDate = Date.civil params[:fromDate]["year"].to_i, params[:fromDate]["month"].to_i, params[:fromDate]["day"].to_i

This just feels wrong. I'll probably have the fields have blanks too.. in which case to_i is bound to barf. This looks like something that must have been done a zillion times before.. So looking for a good recipe for this. I spent the better part of the last hour trying to figure out this quirky rails helper.

A: 

You could make a method that takes one of the date params as an argument :

def date_from_param(params)
  Date.parse("#{params[:year]}#{params[:month]}#{params[:day]}")
end

and then do something like:

from = date_from_param(params[:from_date])
to = date_from_param(params[:to_date])

You can then pass those dates into your query to select the records you want within that range.

_martinS_
A: 

Well yes but its the same thing.. extracted into a method. My issue here was that it didn't feel like the Ruby way.. I was hoping for an easier way to extract the date represented by the select_date tag seems like there isn't.

params[:fromDate][:date] which returns a Date object would have been much better.. since my purpose for using

<%= select_date Time.now, :prefix=>"fromDate"  %>

is to select a date. Ah well..

Gishu