###実現したいこと
元々CakePHPで作成していたシステムをRailsに移行しています。
テーブル内のcreated,modifiedをそのまま利用したいので、created_at,created,updated_at,modifiedすべてに対応する形でデフォルトの設定を変更したいと考えています。
###発生している問題・エラーメッセージ
以下のコードをconfig/initialiersにファイルとして保存しており、
他のサービスでは動いているのですが、今回移行先として作成したプロジェクトで動作しない理由がわかりません。
この記事を元に作ったものです。
↓
https://qiita.com/wakaba260/items/95232b75de86cb5e852e
[set_activerecord_timestamp.rb]
lang
1module TimestampPatch 2 module TableDefinition 3 def timestamps(*args) 4 options = args.extract_options! 5 6 options[:null] = false if options[:null].nil? 7 8 column(:created_at, :datetime, options) 9 column(:updated_at, :datetime, options) 10 column(:created, :datetime, options) 11 column(:modified, :datetime, options) 12 end 13 end 14 15 module SchemaStatements 16 def add_timestamps(table_name, options = {}) 17 options[:null] = false if options[:null].nil? 18 19 add_column table_name, :created_at, :datetime, options 20 add_column table_name, :updated_at, :datetime, options 21 add_column table_name, :created, :datetime, options 22 add_column table_name, :modified, :datetime, options 23 end 24 25 def remove_timestamps(table_name, options = {}) 26 remove_column table_name, :updated_at 27 remove_column table_name, :created_at 28 remove_column table_name, :modified 29 remove_column table_name, :created 30 end 31 end 32 33 module Timestamp 34 def timestamp_attributes_for_update 35 [:updated_at, :modified] 36 end 37 def timestamp_attributes_for_create 38 [:created_at, :created] 39 end 40 end 41end 42ActiveRecord::ConnectionAdapters::TableDefinition.prepend TimestampPatch::TableDefinition 43ActiveRecord::ConnectionAdapters::SchemaStatements.prepend TimestampPatch::SchemaStatements 44ActiveRecord::Base.prepend TimestampPatch::Timestamp
Userモデル(devise利用)が以下の定義であり、
create_table "users", id: :integer, force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC" do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "created", null: false t.datetime "modified", null: false t.index ["email"], name: "index_users_on_email", unique: true t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end
set_activerecord_timestamp.rbをinitializersに入れた状態でUserにデータを追加します。
rails c user = User.new user.email = "aaa@example.com" user.password = "123456" user.save
そうすると以下エラーが発生します。
ActiveRecord::NotNullViolation: Mysql2::Error: Field 'created' doesn't have a default value
エラーの内容はわかるのですが、なぜcreatedに対して変更が適用されないのかの解消ができていません。
お願いします!
###補足情報(言語/FW/ツール等のバージョンなど)
Rails 5.1.4
ruby 2.4.1
gem devise 4.3.0
gem mysql2 0.4.10
回答1件
あなたの回答
tips
プレビュー