Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails timestamps: updated_on / created_on versus created_at / updated_at

I'm writing a Rails migration to create a table:

create_table(TABLE, :options => FEDERATED_TABLE_CONFIG % TABLE) do |table|
  table.timestamps
  table.string :country_tld
end

This results in the following table:

CREATE TABLE `sites` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `country_tld` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=FEDERATED DEFAULT CHARSET=utf8 CONNECTION='mysql://foo:bar@localhost/baz/sites'

Tragically, my foreign data source uses the old-school Rails updated_on and created_on columns for its timestamps. Of course I can get around this:

create_table(TABLE, :options => FEDERATED_TABLE_CONFIG % TABLE) do |table|
  table.datetime :created_on, :updated_on
  table.string :country_tld
end

If there's a trivial way to still use timestamps and get the behaviour I want, I'd love to hear about it. And no, I don't consider monkey-patching ActiveRecord::Timestamp a trivial way of doing it, considering this just affects one migration. ;)

like image 693
Josh Glover Avatar asked Mar 17 '11 12:03

Josh Glover


2 Answers

I'm not entirely sure what your question is here? ActiveRecord::Timestamp will use the created_on and updated_on columns just the same as the _at versions (See lines 84 & 88).

As an aside, you needn't loop through an array to generate the datetimes in a one-liner. Use this instead:

table.datetime :created_on, :updated_on
like image 66
idlefingers Avatar answered Oct 15 '22 20:10

idlefingers


The rails source for timestamps is:

def add_timestamps(table_name)
  add_column table_name, :created_at, :datetime
  add_column table_name, :updated_at, :datetime
end

So you can see there's no way to customize the column names. To be honest, the best way is the one you suggest. I personally avoid stuff like:

%w{created_on updated_on}.each {|col| table.datetime col.to_sym }

And just write out the actual add_column commands, it's more verbose bit also easier to read.

like image 5
jonnii Avatar answered Oct 15 '22 19:10

jonnii