Rails4 3階層のincludesの指定

N+1問題解決のため、includesの設定をしていた。

groupがuserを参照しており、userがdepartmentを参照しているとき、groupからdepartmentをincludesで指定するのにちょっと手間取った。

group → user → department


下記のように書いてもうまくいかなかった

# @groups = Group.order(:id)

@groups = Group.order(:id).
                includes(:user, :department)


下記のように書いたらうまくいった

# @groups = Group.order(:id)

@groups = Group.order(:id).
                includes({user: :department})


参考:
Ruby on Railsあれこれ/findメソッドの:includeオプションの書き方 - 笑猫酒家
N+1問題の対策のため、「Bullet」をインストール - ayaketanのプログラミング勉強日記