0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

railsコンソールでカラムに情報を上書き出来ない、、、

Posted at

目的:user_idカラムがnilのため、1を入れたい

■操作したいデータ

Notification id: 2, shown_from_at: "2021-01-04 02:32:00", shown_to_at: "2021-01-05 02:32:00", subject: "テストだよ", body: "テストテスト", created_at: "2021-01-04 02:32:55", updated_at: "2021-01-04 07:23:28", important_notification: true, user_id: nil

railsコンソール
Notification.find(2).update(user_id: 1)
user_idに1を上書き

  Notification Load (1.4ms)  SELECT "notifications".* FROM "notifications" WHERE "notifications"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
=> false

何が起きているのかを確認

railsコンソール
notification = Notification.find(2)
notification.user_id = 1
notification.valid?
notification.errors.full_messages
railsコンソール
結果は下記になります。
irb(main):017:0> notification = Notification.find(2)
 Notification Load (0.5ms) SELECT "notifications".* FROM "notifications" WHERE "notifications"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
irb(main):018:0> notification.user_id = 1
irb(main):019:0> notification.valid?
=> false
irb(main):020:0> notification.errors.full_messages
=> ["表示期間(from)は不正な値です", "表示期間(to)は不正な値です"]

上記の内容から、「shown_from_at: "2021-01-04 02:32:00", shown_to_at: "2021-01-05」が定義しているフォーマットと違うため、エラーが起きているのではないか?と発覚

指定しているのは「yyyy/mm/dd HH:MM」フォーマットのため、値を入れる際は正しいフォーマットで指定することでエラーを回避できた。

railsコンソール
Notification.find(2).update( shown_from_at: "2021/01/04 02:32",shown_to_at: "2021/01/05 02:32", user_id: 1)
# user_idに1を上書き

  Notification Load (0.3ms)  SELECT "notifications".* FROM "notifications" WHERE "notifications"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
   (0.1ms)  BEGIN

  Notification Update (0.3ms)  UPDATE "notifications" SET "shown_from_at" = $1, "shown_to_at" = $2, "user_id" = $3, "updated_at" = $4 WHERE "notifications"."id" = $5  [["shown_from_at", "2021-01-03 17:32:00"], ["shown_to_at", "2021-01-04 17:32:00"], ["user_id", 1], ["updated_at", "2021-01-04 08:24:25.802888"], ["id", 2]]
   (0.3ms)  COMMIT
=> true
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?