LoginSignup
7
5

More than 3 years have passed since last update.

Rails アソシエーション関連のエラー(ActiveRecord::HasManyThroughOrderError)

Posted at

該当のエラー

ActiveRecord::HasManyThroughOrderError

Cannot have a has_many :through association 'Group#employees' which goes through 'Group#group_employees' before the through association is defined.

実現したいこと 

社員は複数のグループに所属できて、
グループは複数の社員を持っているという風に結びつけたい。
グループに所属している社員。つまり@group.employeesを
実現したい。

原因

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

Groupモデル
class Group < ApplicationRecord  
  has_many :group_employees
  has_many :employees, through: :group_employees
end

と、中間クラスとのアソシエーションを定義するコードを、先に書かないと今回のようになる。

参考

7
5
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
7
5