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 1 year has passed since last update.

投稿したのにidがnilになる

Posted at

自分のメモ用です。
わかりにく個所があると思います。

Createアクションで作成したidがnilになる

記事作成の中で、以下のようにもともと書いていた。

スクリーンショット (39).png

構文に間違いはなく、ただただ投稿するとページが遷移しないので困っていた。

コンソールで確認

コンソールで確認すると下記のように表示され、idやcreate_atといった本来自動で作成されるものが作成されないことが判明。
スクリーンショット (41).png

なので、以下のことを確認。
➀AIに聞く
➁viewでの表示確認(newページとshowページ)
➂データベースの確認

データベースの確認

結果的に言うと、ここが間違っていました。
GenderモデルでUserとGenderをアソシエーションしていました。
さらにcreateアクションでUserと紐づけているにも関わらず、
データベース上で『Userと紐づけていない』ということが発覚!

なので、Addを使用し、下記のように追加しました。

➀rails generate migration AddUserIdToGenders user_id:integer
➁ファイルを確認
➂rails db:migrate

見事紐づけ成功!!
投稿できるようになりました!!

アソシエーションするときは、データベースでの紐づけもしっかり考えてくださいね!

というか、ER図や設計書もしっかり作ればこんなことにはならなかったんだよ。

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?