setoya-blog

システム開発技術、データ分析関連でお勉強したことや、山奥生活を綴る、テンション低めなブログです。

ActiveRecordのincludesに条件を指定する

ActiveRecordのhas_manyなどで持っているassociationをincludesするクエリをかくときに、動的にパラメータを渡してincludesする範囲を絞り込みたいときは、whereを使うと良いのだけど、単純にwhereだけを使わずに、referencesも一緒に使う必要があるらしい。

User.includes(:posts).where('posts.name = ?', 'example')

これだとエラーになり、

User.includes(:posts).where('posts.name = ?', 'example').references(:posts)

これだとエラーにならず意図した動作をする。 includesの引数は、モデルに指定したassociationの名前だけど、referencesに指定する引数はテーブル名にする。

参考情報

ActiveRecord::QueryMethods