よしたく blog

ほぼ週刊で記事を書いています

Railsの中間テーブルを経由してデータ取得ができなかったエラー

tl;dr

  • has_manyを使ってデータを取得したかった
  • has_manyには記述する順番がある

エラー内容

Cannot have a has_many :through association 'Hoge#fuga' which goes through 'Hoge#hoge_fuga' before the through association is defined.

発生の状況

ユーザが持っている本の一覧を中間テーブルを経由して取得したかった。 下記のコードを書いていた。

class User < ApplicationRecord
    has_many :books, through: :user_books
    has_many :user_books
end

解決策

Railsのバージョンが上がってから、has_many の順番が重要になったようで、順番を入れ替えたら解決した。

class User < ApplicationRecord
    has_many :user_books
    has_many :books, through: :user_books
end

参考

qiita.com