将时间戳添加到现有表 [英] Add timestamps to an existing table

查看:59
本文介绍了将时间戳添加到现有表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向现有表添加时间戳 (created_at & updated_at).我尝试了以下代码,但没有用.

I need to add timestamps (created_at & updated_at) to an existing table. I tried the following code but it didn't work.

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

推荐答案

时间戳助手仅在 create_table 块中可用.您可以通过手动指定列类型来添加这些列:

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

虽然这与您在上面指定的 add_timestamps 方法没有相同的简洁语法,但 Rails 仍会将这些列视为时间戳列,并正常更新值.

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.

这篇关于将时间戳添加到现有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆