Active Record will automatically record creation and/or update timestamps of database objects if fields named created_at/created_on or updated_at/updated_on are present.
These columns are automatically created if the scaffold generator is used to create the model. In this case, everything is set up and begins working “out of the box.”
timestamp.rb file:
created_on: date onlycreated_at: date and timeupdated_at/updated_on fieldsleeo: While this is a commonly held convention, I don’t see it referenced in the Rails source anywhere. More importantly, at/on doesn’t actually affect the value or type of data being stored. Rails simply throws a Time in there, which gets cast into a Date if so required by the schema.
Note: timestamp fields are not supported by default. Use a datetime field instead.
Note: Use :timestamp as the column type when defining your migrations. ActiveRecord will automatically convert it to the correct column type for whatever database you run it against.
Note: MUST create these fields Nullable with no default on your database. The value-injector code within timestamp.rb (below) depends upon the initial values of these fields to be NIL and the field to be Nullable.
PostgreSQL note: You need to use timestamp for the created_at et al fields
Q: is this referring to the SQL timestamp data type, or to the MySQL timestamp “feature”?
A: This feature is not dependant on DB-specific automatic timestamping fields/behaviours, it is handled by ActiveRecord.
Q: What is the difference between created_on and created_at if they both have to be datetime fields?
A: There is no difference. The two are treated the same. (They ARE different for Oracle)
(Doesn’t the one save a Time, and the other one a Date object? When you access the created_at or created_on after saving, doesn’t the one give you a Time object, the other a Date object?
—Scott Taylor
)
Q: What if I don’t want updated_at to be automatically handled? I want to update updated_at only in a particular situation…
A: The documentation explains how to disable automatic timestamping.
Q: Why aren’t these fields populated when loading fixtures?
Q: I am struggling with the same question. I loaded a YAML fixture to test and the created_at and updated_at fields won’t take on the values in my YAML file. I even tried it manually in the migration code and it would not work.
category: MagicFieldNames
Q: Why aren’t there answers to these last two?