Sachin srinivasan
Sachin srinivasan

Reputation: 828

Rails ActiveRecord Behaviour?

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.

Upvotes: 0

Views: 56

Answers (1)

EJAg
EJAg

Reputation: 3298

  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).

Upvotes: 1

Related Questions