Reputation: 6243
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
Reputation: 3347
Product.select(:user_id).group(:user_id).order("count(user_id) desc").first.user
can be a solution
Upvotes: 7