Jonathan Clark
Jonathan Clark

Reputation: 20538

Saving custom datetime in the same format as created_at

I am building a Rails 3.2 web app. In this app got a model called Timereport. In this model I got an attribute called reported_at. This used so that that the user reporting the time can select a custom reported_at date to be used.

On the server side I save it like this:

report.reported_at = DateTime.parse(params[:reported_at])

When I use the console I see the date is saved like this:

#<Timereport id: 1583, account_id: 24, created_at: "2014-07-01 10:30:16", updated_at: "2014-07-01 10:30:16", by_admin: true, timereportable_id: 46, timereportable_type: "Project", reported_at: "2014-07-01 00:00:00">

When I get the attribute in the console I get:

t.reported_at
=> Mon, 30 Jun 2014 19:00:00 CDT -05:00

But when I get the updated_at I get:

t.created_at
=> Tue, 01 Jul 2014 05:30:16 CDT -05:00

How can I save the reported_at in the same format as created_at so that it behaves the same way?

Thankful for all help!

Upvotes: 0

Views: 621

Answers (1)

ReggieB
ReggieB

Reputation: 8212

Make sure the reported_at field is a datetime field in the database.

Then rather than giving a text field for users to enter the date and time, use a datetime_select element. This will generate a selection tool that submits the datetime elements in a format that ActiveRecord understands and can convert into the correct format.

You will then not have to DateTime.parse(params[:reported_at]), but just load the data from params in the normal way.

Upvotes: 1

Related Questions