0

I wanted to understand how ActiveRecord works in the following scenario.

@messages = Message.joins(:users).where("some condition").uniq

now if i use @messages.sum(:url_view_count) I see the query is interpreted again as

SELECT DISTINCT SUM ("messages"."url_view_count")  FROM "messages" INNER JOIN "users" ON .. and conditons

why the whole query starts again? Can it do sum among the filtered out @messages right?

And, why the interpreted query is `DISTINCT SUM(url_view_count)'?

Doesn't this mess up my result?

If the column url_view_count has 1, 1, 2. I am expecting 1+1+2 = 4, But this query gives me result as 1+2 = 3.

Please help me understand this.

1 Answer 1

1
  1. @messages is an ActiveRecord::Relation. It's lazy evaluated. So @messages does not execute any SQL commands until it has too. In this case, when you call sum on it.

  2. You have DISTINCT because you chained #uniq there. But I don't think it matters here, because it modifies SUM here (the SQL here selects SUM, not messages).

Sign up to request clarification or add additional context in comments.

2 Comments

Message.pluck(:url_view_count).compact.count , i get 46. Message.pluck(:url_view_count).uniq.compact.count i get 10. so we understand many of values are repeated. Now the .uniq.sum(:url_view_count) from query in question is ignoring repeated values.
#pluck returns Array, and the #uniq here is an array method, but that in your question is an ActiveRecord::Relation method. You'll see that these are very different queries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.