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の関連付けに関するエラーActiveRecord::HasManyThroughOrderErrorについて

Posted at

#1.エラー文
ActiveRecord::HasManyThroughOrderError at /posts
Cannot have a has_many :through association 'Post#tags' which goes through 'Post#tag_relationships' before the through association is defined.

#.2やろうとしていること
タグ機能をつけてpost投稿にタグを一緒に投稿できるようにしたい。

#.3 原因
1.のエラー文を日本語訳してみたところ

has_many :through association 'Post#tags'が、through associationが定義される前に、'Post#tag_relationships'を経由することはできません。

となっていたので

post.rb
 has_many :tags, through: :tag_relationships
 has_many :tag_relationships, dependent: :destroy

中間テーブルと関連づけを定義するコードの順番が逆だということに気づきました。
#4.解決

post.rb
 has_many :tag_relationships, dependent: :destroy
 has_many :tags, through: :tag_relationships

とすることでこのエラーは解決しました!
最後までご覧いただき本当にありがとうございました!

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?