ActiveRecord - 查找具有x个分类的所有记录

时间:2014-03-18 21:37:24

标签: ruby activerecord

我正在试图找出如何编写一个ActiveRecord方法,该方法将返回具有三个以上分类的所有Boats。

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 BoatClassifications < ActiveRecord::Base
  belongs_to :boat
  belongs_to :classification 
end

通常,我无法在AR中的连接模型上查找用于编写查询的资源。如果有人知道任何有用的资源来帮助学习复杂的AR查询,那将非常有帮助。

1 个答案:

答案 0 :(得分:2)

使用分类拳击JOIN 。然后,您需要GROUP BY boats.id ,这样您就可以COUNT为每个不同的船分组了多少行。使用HAVING可以将该条件应用于分组记录。最后,根据需要选择 boat

Boat.joins(:classifications).group("boats.id").having("COUNT(*) > 3").select("boats.*")
相关问题