I think created_at
is always set to the time a record created in by ActiveRecord, but I found some records are created with null created_at
.
Are there any condition to cause this?
3 Answers
These columns created_at, updated_at, created_on, updated_on are automatically handled for you by rails.
However, there are a few notes:
- Do not change the attr's value (i.e.
created_at
should be nil before create and shouldn't be changed before update). Otherwise, ActiveRecord won't update attr's value with the current time. - Check that your
<ClassName>.record_timestamps
is set to true.
Also, I'd suggest to you to add not-null constraint to these columns:
change_column :<table_name>, :created_at, :datetime, :null => false
This way you will be sure that this column always have a not-null value.
Are you using attr_accessible
or attr_protected
on your model?
Because without those basic protections, any update request could be setting these otherwise unvalidated & unprotected attributes.
The only thing i could think of right now is that maybe you are overwriting the created_at
attribute in your view.
<%= t.text_field :created_at %>
And the value you are passing when submitting the form is not being correctly converted by ActiveRecord, becoming nil
.
The created_at
is not meant to be manipulated, it is better to create another field like creation_date
and leave it to be populated by default.
But this is just a guess.
updated_at
in question title andcreated_at
in the body. Which one are you talking about?created_at
was migrated in after those records already existed?