James Croft

MySQL created_at and updated_at triggers

Use the following SQL to add triggers to MySQL to ensure the created_at and updated_at fields are always set correctly.

Replace TABLE_NAME with the name of the table.

CREATE TRIGGER TABLE_NAME_create BEFORE INSERT ON `TABLE_NAME` FOR EACH ROW SET NEW.created_at = NOW(), NEW.updated_at = NOW();
CREATE TRIGGER TABLE_NAME_update BEFORE UPDATE ON `TABLE_NAME` FOR EACH ROW SET NEW.updated_at = NOW(), NEW.created_at = OLD.created_at;

When working with PostgreSQL I normally use the Sequel Postgresql Triggers gem to do something similar.