This project is archived and is in readonly mode.

#6789 new
Jim Haungs

Arel sum not honoring limit

Reported by Jim Haungs | May 19th, 2011 @ 02:01 AM

Given a table of items with a cost column, the following code sums ALL of the items for the cart, not just 2. For this simplified example, assume I want to discount the two most expensive items, i.e., order is 'cost desc'.

cart.line_items.limit(2).sum(:cost)

The generated SQL applies the limit after the sum instead of creating a subquery.

e.g.: select sum(cost) from (select cost from line_items where cart_id = N limit 2);

The following code works correctly, but SQL sum cannot be used to let the database do the work.

cart.line_items.limit(2).inject(0) {|sum, each| sum + each.cost}

Can this be expressed in Arel?

Comments and changes to this ticket

  • Steven Soroka

    Steven Soroka May 20th, 2011 @ 03:44 AM

    • Tag changed from arel rails3 sum limit sql to arel rails3 sum limit sql, invalid

    Since Arel's job is essentially to generate the sql you need, and the sql you are trying to generate is not valid, it doesn't make sense to expect arel to magically fall back to Ruby to complete your request.

    The proper place for this is in your model class, where you can do the request without the sum, and sum it in ruby like you've shown.

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Pages