我正在努力找到所有船长不有船的分类帆船。我可以找到所有带帆船的船长,但无法弄清楚如何使用ActiveRecord进行反向操作。
class Captain < ActiveRecord::Base
has_many :boats
end
class Boat < ActiveRecord::Base
belongs_to :captain
has_many :boat_classifications
has_many :classifications, through: :boat_classifications
end
class BoatClassification < ActiveRecord::Base
belongs_to :boat
belongs_to :classification
end
答案 0 :(得分:2)
如果你不介意一点sql,你可以让船长加入他们的船只和分类,然后选择那些没有帆船的人。
Captain.joins("
LEFT JOIN boats ON captains.id = boats.captain_id
LEFT JOIN boat_classifications ON boats.id = boat_classifications.boat_id
LEFT JOIN classifications ON boat_classifications.classification_id = classifications.id AND classifications.name = 'Sailboat'
").where("classifications.id IS NULL")
或者使用现有的并使用sql选择不在该组中的队长
Captain.where("id NOT IN (?)", Captain.sailors.map(&:id))