LoginSignup
2
1

More than 3 years have passed since last update.

何でbelongs_to :userになるか?(忘備録)

Posted at

はじめに

ActiveRecord::AssociationNotFoundError in Tweet#index」エラー向けの記事になります。
エラー勉強会の復習した時に、疑問に思ったのでアウトプットしてみました。
Associationと出てる時点で、DBの問題であると考える事ができますが、今回は掘り下げてみたいと思います。

スクリーンショット 2020-03-01 20.55.55.png

エラーの意味

エラーの通りで、tweet_controllerのindexアクションでAssociationが見つからないエラーです。

Associationとは

DBに構築されているテーブルの関連付ける事を指しています。

今回は、下図のようなAssciationを組んでいる時に起こるエラーとなります。

スクリーンショット 2020-03-01 20.59.37.png

まずは、tweet_controllerのindexアクションをみてみます。

app/controllers/tweet_controller.rb
スクリーンショット 2020-03-01 21.07.57.png

記述に問題はありませんが、SQLを読み込むincludeメソッドにエラーが起きている事が分かります。
:userはUserモデルの事を指しているので、 Userモデルを見てみます。

app/models/user.rb
スクリーンショット 2020-03-01 21.51.39.png

記述に問題はなさそうです。

has_manyの復習すると、 has_many モデル名(複数) という記述をします。
userはtweetとcommentの1対多の関係になります。

そうすると、他のtweetモデルかcommentモデルに問題があると考えます。

app/models/tweet.rb

スクリーンショット 2020-03-01 21.55.09.png

app/models/comment.rb
スクリーンショット 2020-03-01 21.57.17.png)

ようやくエラー元を見つけました。 belongs_to :usersが悪さをしていました。

belongs_to モデル名(単数) と定義されます。
ここで :users ⇨ :user に直すとエラーが解消されます。

tweetモデルとuserモデルが、associationができていなかった為にエラーが出てたようです。

参照文献:railsガイド

2
1
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
2
1