Can Rails automatically parse date and time retrieved from text_field form

Can Rails automatically parse the date and time received from the form text field?

# in view
<div class="field">
  <%= f.label :created_at %><br />
  <%= f.textfield :created_at %>
</div>

# in controller
params[:product][:updated_at].yesterday

I am currently getting the following error:

undefined method `yesterday' for "2010-04-28 03:37:00 UTC":String
+5
source share
1 answer

If you put this parameter in the model directly, as the code of the rail generator template does, it ActiveRecordwill take care of this for you

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

Also, 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, it .civil_from_formatdoes not work as you expected with daylight saving time.

+1
source

All Articles