ピスタチオを食べながらrailsを楽しむ

ピスタチオ大好きな著者のrailsを使ったツール作成の日記です。

2つ先のassociationテーブルをjoinしwhereする

特定のmodelの関連先のフィールドに対してクエリを掛けたいケースへの対応。

以下のようなmodelがあるとする。

# app/models/book.rb

class Book < ActiveRecord::Base
  has_many :authors
end

class Author < ActiveRecord::Base
  has_many :author_books
  accepts_nested_attributes_for :author_books
end

class AuthorHistory < ActiveRecord::Base
  belongs_to :author
end

class AuthorHistoryBooks < ActiveRecord::Base
  belongs_to :book
  belongs_to :author_history
end

この場合にbooksテーブル内から、authorテーブルのカラムとauthor_history_booksテーブルのカラムに対してwhereした結果が欲しいというケース。

Book.includes(authors: :author_history_books)

こうすることでauthorsテーブルだけでなくauthor_history_booksテーブルのカラムにもwhere出来る。

modelは適当。