LoginSignup
6
8

More than 5 years have passed since last update.

activerecord のtimestampにdefault設定をする

Last updated at Posted at 2016-03-25
  • 前提
    • rakeが使えること

table情報を作る

$ bundle exec rake db:create_migration NAME=create_monitoring_logs

ソース更新

$ vi db/migrate/YYYYMMDD014656_create_monitoring_logs.rb

class CreateMonitoringLogs < ActiveRecord::Migration

CREATE_TIMESTAMP = 'DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'
UPDATE_TIMESTAMP = 'DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'

  def up
    create_table :monitoring_logs do |t|
      t.integer  :level
      t.bigint  :app_time
      t.text     :body
      t.column :created_at, CREATE_TIMESTAMP
      t.column :updated_at, UPDATE_TIMESTAMP
    end
  end

  def down
    drop_table :monitoring_logs
  end

end

migrateする

$ bundle exec rake db:migrate

table情報を見てみる

$ show create table monitoring_logs;

| monitoring_logs | CREATE TABLE `monitoring_logs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `level` int(11) DEFAULT NULL,
  `app_time` bigint(20) DEFAULT NULL,
  `body` text,
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

  • 結果 timestampsマジクソだった!
6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8