1

I'm studying Redmine application by Rails.

I make the query as below:

re = Issue.select("sum(id) as test_total").group("tracker_id")

But I can not get the 'total_price' value. Here's the result of 're.inspect'

[#<Issue >, #<Issue >, #<Issue >]

It's only array of empty Issue objects.

Then I see the query in log:

SELECT sum(id) as test_total FROM "issues" GROUP BY tracker_id

If I run this query by database console, the result is:

| test_total |
-------------
|     1      |
-------------
|     2      |
-------------
|     3      |
-------------

It's 3 rows of result.

The previous 're' has 3 elements but each element is one empty Issue object.

How can I get 'total_price' from 're'?

Thank you.

vietstone
  • 8,784
  • 16
  • 52
  • 79
  • 2
    I know I've answered this before but I can't find the duplicate right now. Summary: `inspect` shows you the column values that match the underlying table's schema. The table has no `test_total` so it won't show up in `inspect` output. The objects in `re` will have `test_total` methods though and they'll be created via `method_missing`. So you can say `re.map(&:test_total)` and it will work. – mu is too short Aug 11 '14 at 17:05
  • @muistooshort Your answer is more perfect. I am deleting mine, could you add your answer. I answered, as I know this behavior in Rails. But never tried to see source code.. – Arup Rakshit Aug 11 '14 at 17:10
  • @ArupRakshit: I'd rather find the duplicate to avoid cluttering the site. – mu is too short Aug 11 '14 at 18:23
  • @muistooshort Okay.. I will wait to see that then. – Arup Rakshit Aug 11 '14 at 18:24
  • Apologies @muistooshort, I didn't see your comment before answering. – A Fader Darkly Aug 11 '14 at 19:06
  • I can't find the duplicate I'm thinking off, that one is close enough though. – mu is too short Aug 11 '14 at 21:10

1 Answers1

1

Firstly:

re.all.map &:attributes

will show you the attributes you have available.

Secondly, why are you looking for 'total_price' when your query creates a sum called 'test_total'?

re.first.test_total

should do it.

If you want the total of the totals:

re.all.map(&:test_total).inject(:+)

'map' creates a new array from an old one by processing a block. &:test_total is short-hand for { |i| i.test_total }, creating an array of test_total values. Inject performs an operation on a variable that's passed through to each iteration of the loop. In this case it's calling the '+' method on the passed variable and each array member. For a deeper explanation, see here:

How does "(1..4).inject(&:+)" work in Ruby

Community
  • 1
  • 1
A Fader Darkly
  • 3,516
  • 1
  • 22
  • 28