Add timestamps to an existing table

2019-01-21 01:48发布

I need to add timestamps (created_at updated_at) to an existing table. I tried the following code but it didn't work. I have also tried other solutions I found online but they don't work either.

class AddTimestampsToUser < ActiveRecord::Migration
    def change_table
      add_timestamps(:users)
    end
end

How can I do it?

14条回答
小情绪 Triste *
2楼-- · 2019-01-21 02:16

It's change, not change_table for Rails 4.2:

class AddTimestampsToUsers < ActiveRecord::Migration
  def change
    add_timestamps(:users)
  end
end
查看更多
甜甜的少女心
3楼-- · 2019-01-21 02:20

The answers before seem right however I faced issues if my table already has entries.

I would get 'ERROR: column created_at contains null values'.

To fix, I used:

def up
  add_column :projects, :created_at, :datetime, default: nil, null: false
  add_column :projects, :updated_at, :datetime, default: nil, null: false
end

I then used the gem migration_data to add the time for current projects on the migration such as:

def data
  Project.update_all created_at: Time.now
end

Then all projects created after this migration will be correctly updated. Make sure the server is restarted too so that Rails ActiveRecord starts tracking the timestamps on the record.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-21 02:21

For those who don't use Rails but do use activerecord, the following also adds a column to an existing model, example is for an integer field.

ActiveRecord::Schema.define do
  change_table 'MYTABLE' do |table|
    add_column(:mytable, :my_field_name, :integer)
  end
end
查看更多
不美不萌又怎样
5楼-- · 2019-01-21 02:22

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.

查看更多
叛逆
6楼-- · 2019-01-21 02:24

add_timestamps(table_name, options = {}) public

Adds timestamps (created_at and updated_at) columns to table_name. Additional options (like null: false) are forwarded to #add_column.

class AddTimestampsToUsers < ActiveRecord::Migration
  def change
    add_timestamps(:users, null: false)
  end
end
查看更多
The star\"
7楼-- · 2019-01-21 02:25

Nick Davies answer is the most complete in terms of adding timestamp columns to a table with existing data. Its only downside is that it will raise ActiveRecord::IrreversibleMigration on a db:rollback.

It should be modified like so to work in both directions:

def change
  add_timestamps :campaigns, default: DateTime.now
  change_column_default :campaigns, :created_at, from: DateTime.now, to: nil
  change_column_default :campaigns, :updated_at, from: DateTime.now, to: nil
end
查看更多
登录 后发表回答