I need to add timestamps (created_at
& updated_at
) to an existing table. I tried the following code but it didn\'t work.
class
I'm on rails 5.0 and none of these options worked.
The only thing that worked was using the type to be :timestamp and not :datetime
def change
add_column :users, :created_at, :timestamp
add_column :users, :updated_at, :timestamp
end
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.
This is a simple one to add timestamp in existing table.
class AddTimeStampToCustomFieldMeatadata < ActiveRecord::Migration
def change
add_timestamps :custom_field_metadata
end
end
This seems like a clean solution in Rails 5.0.7 (discovered the change_column_null method):
def change
add_timestamps :candidate_offices, default: nil, null: true
change_column_null(:candidate_offices, :created_at, false, Time.zone.now)
change_column_null(:candidate_offices, :created_at, false, Time.zone.now)
end
not sure when exactly this was introduced, but in rails 5.2.1 you can do this:
class AddTimestampsToMyTable < ActiveRecord::Migration[5.2]
def change
add_timestamps :my_table
end
end
for more see "using the change method" in the active record migrations docs.
Your original code is very close to right, you just need to use a different method name. If you're using Rails 3.1 or later, you need to define a change
method instead of change_table
:
class AddTimestampsToUser < ActiveRecord::Migration
def change
add_timestamps(:users)
end
end
If you're using an older version you need to define up
and down
methods instead of change_table
:
class AddTimestampsToUser < ActiveRecord::Migration
def up
add_timestamps(:users)
end
def down
remove_timestamps(:users)
end
end