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条回答
再贱就再见
2楼-- · 2019-01-21 02:38

I made a simple function that you can call to add to each table (assuming you have a existing database) the created_at and updated_at fields:

  # add created_at and updated_at to each table found.
  def add_datetime
    tables = ActiveRecord::Base.connection.tables
    tables.each do |t|
      ActiveRecord::Base.connection.add_timestamps t  
    end    
  end
查看更多
唯我独甜
3楼-- · 2019-01-21 02:41

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
查看更多
登录 后发表回答