Rails 2.3 select_date:选择参数的首选方法

时间:2011-02-20 18:25:06

标签: ruby-on-rails ruby

如何从select_date助手中正确获取参数?我的版本非常有用和功能。通过参数的日期没有前缀0。因此,1月份是1,我需要它为01.这样,当我搜索数据库时,我得到1月而不是11月 我的控制器代码如下。

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  

       start=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

我的观看代码是

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

我使用的是rails 2.3.10和ruby 1.8.7。这又有效,但远非理想或惯用。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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