@cart = CartItem.sum(:quantity, :group => "cart_id") new_ids = [] @cart.each do |c| new_ids << c[0] if c[1].to_i > 6 end
Refactorings
No refactoring yet !
steved
August 21, 2010, August 21, 2010 16:58, permalink
This is a case where you need to let sql do the work.
sql = "select cart_id, sum(quantity) as sum_quantity from cart_items group by cart_id having sum_quantity > 6" result = ActiveRecord::Base.connection.select_rows(sql) #=> [[1, 7], [3, 22]] ids = result.map(&:first) #=> [1, 3]
Adam
August 22, 2010, August 22, 2010 02:53, permalink
I disagree that you want to drop down to raw SQL here, though steved is right that you do want to let your RDBMS do the work.
CartItem.group(:cart_id).where('quantity > 6').sum(:quantity)
# => #<OrderedHash {1=>16, 2=>12}>
steved
August 23, 2010, August 23, 2010 03:01, permalink
Adam: you're assuming Rails 3.0, right? Also, I believe your code will exclude ROWS where quantity > 6 rather than CART_ID's whose sum(quantity) > 6
Adam
August 23, 2010, August 23, 2010 03:07, permalink
You would be correct. Misread the requirements. And yes, Rails 3. No reason to not be developing on it now.
CartItem.group('cart_id').having('quantity > 6').sum(:quantity)
Paddy
August 25, 2010, August 25, 2010 18:20, permalink
Hi Adam,
Thank you for the re-factoring and can you please let me know the compatible code for 2.3.5.
Thank you!
Paddy
Vincent Durand
October 25, 2010, October 25, 2010 18:06, permalink
Rails 2.3.5 compatible solution.
ids = CartItem.sum(:quantity, :group => 'cart_id', :having => 'sum_quantity > 6').keys
What i want to do is, find the sum of a column (quantity) grouped_by cart_id and it should list only the cart items having a total quantity greater than 6. The below code does the job ...but can it be achieved in a better way?
Please do let me know.
Thank you!
Paddy