Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord - Finding all objects with shared attributes in a join model

I have three models

class Boat < ActiveRecord::Base
  belongs_to  :captain
  has_many    :boat_classifications
  has_many    :classifications, through: :boat_classifications
end

class Classification < ActiveRecord::Base
  has_many :boat_classifications
  has_many :boats, through: :boat_classifications
end

class BoatClassification < ActiveRecord::Base
  belongs_to :boat
  belongs_to :classification
end

I'm trying to write a simple ActiveRecord query to find all the boats of type sailboat. Something like Boat.where(classifications: "Sailboat")

like image 890
Arel Avatar asked Mar 18 '14 15:03

Arel


1 Answers

I think this could work:

Boat.joins(:classifications).where(classifications: { name: 'Sailboat' }) # name or whatever field contains Sailboat

Generates this query:

SELECT `boats`.* FROM `boats` INNER JOIN `boat_classifications` ON `boat_classifications`.`boat_id` = `boats`.`id` INNER JOIN `classifications` ON `classifications`.`id` = `boat_classifications`.`classification_id` WHERE `classification`.`name` = 'Sailboat'
like image 87
backpackerhh Avatar answered Oct 10 '22 09:10

backpackerhh