Given the canonical example:
class Post < ActiveRecord::Base
has_many :comments
end
class Comments < ActiveRecord::Base
belongs_to :post
end
I would like to return a scope (i.e. ActiveRecord::Relation
) of all the Posts that have X or fewer Comments; using either using Active Record Query Interface, Arel or something else if it solves my problem.
Pseudocode:
scope :quiet, lambda { |n| where(comments: { maximum: n }) }
I am aware that this can be done in Ruby with a simple Enumerable#select
. It is preferable to be calculated on the database as in actuality there can only ever be one Model that satisfies the predicate.