How do you properly get the parameters from the select_date helper? My version is very contrived and functions. The dates that come through the parameters do not have the prefix 0's. So January is 1 and I need it to be 01. That way when I search the db I get January and not November.
My controller code is below.def daterange
if params[:start_dateCommence] && params[:end_dateCommence]
start_date=params[:start_dateCommence] #params from view can be accessed individually as params[:start_date][:month]
end_date = params[:end_dateCommence] #params from view
star开发者_开发百科t=start_date.values_at("year","month","day") #creates an array of the values Y M D for the end range
endd=end_date.values_at("year","month","day") #creates an array of the values Y M D for the end range
startStr=""
endStr=""
for e in start # for each in start array create a string in the format yyyy-mm-dd
if e.length <2
e="0"+e #this is required so days and months have prepending 0'
end
startStr=startStr+e+"-"
end
for e in endd
if e.length<2
e="0"+e
end
endStr=endStr+e+"-"
end
@startStr=startStr.chop #chops off "-" at end of string
@endStr=endStr.chop
if ($startStr || $endStr)!="0-0-0"
@leases=Lease.find_by_sql ["SELECT * FROM leases WHERE commencement_date >= ? AND commencement_date <= ? ORDER BY commencement_date ASC",$startStr ,$endStr]
end
end
and my view code is
<% form_tag ({:controller => 'leases', :action => "daterange"}) do %><h4>Commencement Date:</h4>
Start:<%= select_date nil, :prefix=>:start_dateCommence, :include_blank => true,:order => [:year,:month, :day]%>
End:<%= select_date nil ,:prefix => :end_dateCommence,:include_blank => true,:order => [:year,:month, :day]%>
<%= submit_tag("Reset", { :name => 'reset', :id => 'reset_button', :type => "reset" }) %>
<%= submit_tag "Submit", :disable_with => "Submitting..." %>
I am using rails 2.3.10 and ruby 1.8.7. Again this works but is far from ideal or idiomatic.
You could do something like this:
def daterange
start_default = '1900-01-01' # pick some reasonable default
endd_default = '2099-01-01' # pick some reasonable default
start = Time.parse(params[:start_dateCommence].values_at(:year, :month, :day).join('-')).to_date rescue start_default
endd = Time.parse(params[:end_dateCommence].values_at(:year, :month, :day).join('-')).to_date rescue endd_default
@leases = Lease.find_by_sql ["SELECT * FROM leases WHERE commencement_date >= ? AND commencement_date <= ? ORDER BY commencement_date ASC", start , endd]
end
精彩评论