ActiveRecord - 在连接模型中查找具有共享属性的所有对象

时间:2014-03-18 15:47:56

标签: ruby activerecord

我有三个模特

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

我试图编写一个简单的ActiveRecord查询来查找所有类型帆船的船只。像Boat.where(classifications: "Sailboat")

这样的东西

2 个答案:

答案 0 :(得分:3)

我想你想要这样的东西:

Boat.includes(:classifications).where(classifications: {id: Classification.sailboats})

要实现这一点,您还需要Classification这样的范围:

def self.sailboats
  where(name: "Sailboat")
end

答案 1 :(得分:3)

我认为这可行:

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

生成此查询:

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'