Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Arel sum not honoring limit

#6789

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?

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

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. Steven Soroka
    Steven Soroka
    • 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.

    May 20th, 2011 @ 03:44 AM