Developer
Developer

Reputation: 6243

Rails: How to find out which parent object has maximum children records

These are the two models I am working with,

User model

class User < ActiveRecord::Base
  has_many :products
end

Product model

class Product < ActiveRecord::Base
  belongs_to :user
end

Now I want to find out which user has maximum number of products.

I know I can find out by constructing a loop for users and associated products, but is there a way to find out by active record query?

Upvotes: 1

Views: 1161

Answers (1)

Fer
Fer

Reputation: 3347

Product.select(:user_id).group(:user_id).order("count(user_id) desc").first.user can be a solution

Upvotes: 7

Related Questions