LoginSignup
78
42

More than 5 years have passed since last update.

Rails アソシエーション関連のエラー(has_many throughが通らない)

Posted at

該当のエラー

ActiveRecord::HasManyThroughOrderError

Cannot have a has_many :through association 'Micropost#meats' which goes through 'Micropost#post_tags' before the through association is defined.

なかなか検索掛けてもでなかったので後に役立てばうれしい

事例 

railstutorialからオリジナル派生で飲食関連のアプリケーションを作成中

https://qiita.com/tobita0000/items/daaf015fb98fb918b6b8
↑のありがたい記事を参考に

ポストモデル(micropost)にお肉モデル(meat)をタグ付けする形で投稿したいので
中間モデル(post_tag)を経由して上2モデル間のアソシエーションを結びたい

micropostモデル
class Micropost < ApplicationRecord


  has_many :meats , through: :post_tags
  has_many :post_tags , dependent: :destroy
end
中間モデル
class PostTag < ApplicationRecord
    belongs_to :micropost
    belongs_to :meat
    has_one :favorite
    validates :micropost_id , presence: true
    validates :meat_id , presence: true
end
お肉モデル
class Meat < ApplicationRecord
   validates :name , presence: true , length: { maximum: 20}
   has_many :microposts , through: :post_tags
   has_many :post_tags , dependent: :destroy
end

で、Micropost#create時にエラー。
どうやら中間モデルより先の目当てのモデルまでthroughしきれてないみたいだ。

原因

https://github.com/rails/rails/issues/29123
↑参考

同じエラーを持ってる人が結構いた。
事例としては
Rails 5.0.0辺りから5.1.0辺りにアップグレードすると途端にエラーが出る方が多そうな印象。
よって考えられるのはrailsの仕様が変わっている模様。

micropostモデル
class Micropost < ApplicationRecord


  has_many :meats , through: :post_tags
  has_many :post_tags , dependent: :destroy
end

エラーメッセージにある通り
HasManyThroughOrderError
文字通りの順番(Order)が原因らしい

micropostモデル
class Micropost < ApplicationRecord

 has_many :post_tags , dependent: :destroy
 has_many :meats , through: :post_tags

end

と、中間クラスとのアソシエーションを定義するコードを、先に書くようにすることが肝らしい。

以上です。

78
42
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
78
42