Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Rails automatically parse datetime received from form text_field

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
like image 274
Alexey Zakharov Avatar asked Nov 14 '22 07:11

Alexey Zakharov


1 Answers

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.

like image 79
SooDesuNe Avatar answered Dec 30 '22 04:12

SooDesuNe