9

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?

5
  • You say updated_at in question title and created_at in the body. Which one are you talking about?
    – KL-7
    Nov 30, 2011 at 10:02
  • Perhaps created_at was migrated in after those records already existed?
    – Chowlett
    Nov 30, 2011 at 10:05
  • No, these records are saved after all migrations.
    – yaotti
    Nov 30, 2011 at 10:09
  • 4
    No answer! That's shocking, I am having this issue as well! Time to dig deeper.
    – RubyDubee
    Jul 10, 2012 at 16:00
  • 1
    Can you provide any more context for your question? Models, schema, relevant code? I've never seen this happen in any of my rails projects. Sep 25, 2012 at 15:55

3 Answers 3

1

These columns created_at, updated_at, created_on, updated_on are automatically handled for you by rails.

However, there are a few notes:

  1. 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.
  2. 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.

1

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.

Mass-assignment security

0

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.