Reputation: 2103
So i do have User model and Cart model. obviously
User has_many :carts
and what i intend to do is selecting only users with specific carts count. I really want to have it in pure rails-like-sql so i started with this:
User.joins(:carts).group(:id).count
which gave me a hash with pretty much all the information i need (user id and how many carts). however i dont want to browse again thorugh this hash, is there another smart and clean way?
Essentially I expect to get an ActiveRecord::Relation
with users who have more than 3 carts
Upvotes: 1
Views: 44
Reputation: 52357
To return AR with users, who have more, that 3 carts you would want to use having
clause:
User.joins(:carts).group('users.id').having('count(carts.id) > 3')
Upvotes: 1
Reputation: 7167
You don't need to join for that:
Cart.group(:user_id).count
What do you mean when you say "browse"?
Upvotes: 0