6de3daa3f91b7169c85df7702b4fb1d4

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

@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 !

B8ba61cc84ecb63c859435be28547dfb

steved

August 21, 2010, August 21, 2010 16:58, permalink

No rating. Login to rate!

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]
A8d3f35baafdaea851914b17dae9e1fc

Adam

August 22, 2010, August 22, 2010 02:53, permalink

No rating. Login to rate!

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}>
B8ba61cc84ecb63c859435be28547dfb

steved

August 23, 2010, August 23, 2010 03:01, permalink

No rating. Login to rate!

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

A8d3f35baafdaea851914b17dae9e1fc

Adam

August 23, 2010, August 23, 2010 03:07, permalink

No rating. Login to rate!

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)
6de3daa3f91b7169c85df7702b4fb1d4

Paddy

August 25, 2010, August 25, 2010 18:20, permalink

No rating. Login to rate!

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

2ae5c08e0acf52951e10006f14a56a83

Vincent Durand

October 25, 2010, October 25, 2010 18:06, permalink

No rating. Login to rate!

Rails 2.3.5 compatible solution.

ids = CartItem.sum(:quantity, :group => 'cart_id', :having => 'sum_quantity > 6').keys

Your refactoring





Format Copy from initial code

or Cancel