Rails Recipe for Date Range in View

I need to take a date range from the UI, get records in that range, and plot it. 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 needed to do to restore 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

      

It just isn't right. ... The fields probably have spaces too. In this case, to_i is bound to barf. It's like something that must have been done a million times before ... So look for a good recipe for this. I've spent most of the last hour trying to figure out this quirky rail mate.

0


source to share


2 answers


You can make a method that takes one of the date parameters 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 to your query to select the records you want in that range.

0


source


Well yes, but it's the same ... extracted into a method. My problem was that this doesn't seem like the Ruby way. I was hoping that an easier way to extract the date represented by the select_date tag seems to be not.

params[:fromDate][:date]

which returns a Date object would be much better .. as my purpose of using



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

      

- choose a date. Good..

0


source







All Articles