Sarindipity
Sarindipity

Reputation: 265

Rails: setting column default to created_at timestamp

I am using a Postgres DB with Rails v4.1.6

I have a table with a start_time column.

I want the start_time column to be non null and have a default value of the timestamp that will be the value in created_by.

My understanding is that the timestamp value for created_by (and updated_at) are created by Rails and not enforced by the DB (please let me know if this is wrong). If there a way to match these two columns up? Is there a way to have the DB enforce it?

My only solution right now is to use a before_create filter (but I think there would be inconsistencies between the two values).

Upvotes: 2

Views: 1288

Answers (1)

Sarindipity
Sarindipity

Reputation: 265

I want to thank @Alireza and @nikkon226 for perspective on this question.

The solution I am using now is to modify the start_time in a before_create filter. In before_create (at least in Rails v4.1.6) the timestamps have already been set. It is better to modify the record in before_create rather than after_create because it saves us at least 1 save call.

Of course with this solution I no longer can put a validation of presence for start_time because validation happens before save/create.

If anyone has a better solution please share.

Upvotes: 2

Related Questions