找到与ActiveRecord的反向关系

时间:2014-03-19 19:40:01

标签: ruby-on-rails ruby activerecord

我正在努力找到所有船长有船的分类帆船。我可以找到所有带帆船的船长,但无法弄清楚如何使用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

1 个答案:

答案 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))