Search code examples
ruby-on-railsactiverecordactive-record-query

How do I query with '.includes' across more than two tables?


I have the following associations:

class Captain
  has_many :boats
end

class Boat
  belongs_to :captain
  has_many :classifications
end

class Classification
  has_many :boats
end

I want to find out which captains have boats that have classifications with :name attributes of "catamaran."

This has been my best guess so far: Captain.includes(:boats, :classifications).where(:boats => {:classifications => {:name => "catamaran"}})


Solution

  • Try this

    Captain.joins(boats: :classifications).where(classifications: { name: "catamaran" })
    

    This query results in following SQL query

    SELECT * FROM `captains` 
       INNER JOIN `boats` ON `boats`.`captain_id` = `captains`.`id` 
       INNER JOIN `join_table` ON `join_table`.`boat_id` = `boat`.`id`     
       INNER JOIN `classifications` ON `join_table`.`classification_id` = `classifications`.id