Ruby on Rails Thursday, December 5, 2013



On Wednesday, 4 December 2013 19:00:31 UTC-5, Ruby-Forum.com User wrote:
Solved (though I'm not entirely sure why this works):

UtilityDatum.
  select("sum(ami_residential)").
  where(:utility => u).
  group("utility_id").
  reorder('').
  first

The reorder() prevents the ORDER BY clause from being emitted, so the
generated SQL is valid.

--
Posted via http://www.ruby-forum.com/.

The 'ORDER BY' and 'LIMIT' clauses are actually coming from the `first` call on the end of the chain.

For what it's worth, if the first query you mentioned is the one you want you may want to check out `ActiveRecord::Calculations`, in particular `sum`:

http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-sum

Your code would look like:

 r = u.utility_data.group(:utility_id).sum(:ami_residential)

At this point, `r` is a Hash:

{ 42 => 127.25, 76 => 321.02, etc }

of utility_id => sum pairs.

If you just want data rolled up for *one* Utility (I'm guessing that's what `u` in the code above is...) you could skip the group:

sum = u.utility_data.sum(:ami_residential)

This returns a single number, the sum for all the related records.

--Matt Jones 

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/11bc5cd1-0594-4fef-8e33-7f8aae0432fb%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment