4

params[:date]将字段转换为Date对象的最优雅方式是什么?

"date"=>{"day"=>"13", "year"=>"2012", "month"=>"4"}

目前,我有以下代码controller

@date = Date.current
if params[:date]
  yy = mm = dd = 0
  yy = params[:date][:year].to_i  if params[:date][:year]
  mm = params[:date][:month].to_i if params[:date][:month]
  dd = params[:date][:day].to_i   if params[:date][:day]
  @date = Date::civil(yy, mm, dd) if Date::valid_date?(yy, mm, dd)
end

和里面viewform_tag

<%= select_date(@date, :order => [:year, :month, :day], :prefix => 'date') %>
4

1 回答 1

8

It will return the valid date or time object . Try :

@date = Date.parse("#{params[:date]['day']}-#{params[:date]['month']}-#{params[:date]['year']}") if params[:date]
OR
@date = Time.parse("#{params[:date]['day']}-#{params[:date]['month']}-#{params[:date]['year']}") if params[:date]

@date ||= Date.current
于 2012-04-13T06:53:48.680 回答