Add timestamps to an existing table
Migrations are just two class methods (or instance methods in 3.1): up
and down
(and sometimes a change
instance method in 3.1). You want your changes to go into the up
method:
class AddTimestampsToUser < ActiveRecord::Migration
def self.up # Or `def up` in 3.1
change_table :users do |t|
t.timestamps
end
end
def self.down # Or `def down` in 3.1
remove_column :users, :created_at
remove_column :users, :updated_at
end
end
If you're in 3.1 then you could also use change
(thanks Dave):
class AddTimestampsToUser < ActiveRecord::Migration
def change
change_table(:users) { |t| t.timestamps }
end
end
Perhaps you're confusing def change
, def change_table
, and change_table
.
See the migration guide for further details.
The timestamp helper is only available in the create_table
block. You can add these columns by specifying the column types manually:
class AddTimestampsToUser < ActiveRecord::Migration
def change_table
add_column :users, :created_at, :datetime, null: false
add_column :users, :updated_at, :datetime, null: false
end
end
While this does not have the same terse syntax as the add_timestamps
method you have specified above, Rails will still treat these columns as timestamp columns, and update the values normally.