Search code examples
ruby-on-railscountruby-on-rails-5finder

How do I write a Rails finder method that counts instances of a field?


I'm using Rails 5. I have a model with

class User < ApplicationRecord
    ...
    has_many :emails

How do I write a finder method that locates all the users who have more than one email? I can't seem to figure out how to use "count" in a where clause.


Solution

  • This will join on the emails table and return users having a count of more than one.

    scope :with_more_than_one_email, -> {
      joins(:emails).having('COUNT(emails) > 1').group(:id)
    }
    

    You can invoke it with User.with_more_than_one_email