Can Rails automatically parse datetime received from form text_field

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

Can Rails automatically parse a datetime received from a form's text_field?

# in view <div class="field">   <%= f.label :created_at %><br />   <%= f.textfield :created_at %> </div>  # in controller params[:product][:updated_at].yesterday 

Currently I'm get following error:

undefined method `yesterday' for "2010-04-28 03:37:00 UTC":String 

回答1:

If you are putting that param into a model directly, as the rails generator boilerplate code does, ActiveRecord takes care of that for you

def create     @product = Product.new(params[:product])     @product.updated_at.yesterday #will succeed     #rest of method end 

Other than that you are stuck with something like:

DateTime.parse(params[:product][:update_at]) 

or

DateTime.civil_from_format(:local, year, month, day, hour, minutes, seconds) 

But, in my experience .civil_from_format doesn't work as you'd expect with daylight savings time.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!