I have encountered some strange behavior of ActiveRecord Relation recently.
Suppose, I have a Stat
model with the following properies:
clicks
views
created_at
- and others
Further suppose I have the following scope:
scope :aggregated, select('SUM(clicks) as clicks, SUM(views) as views).group('DATE(created_at)')
As a result I expect to get an array of Stat object with info aggregated by day, and so it is. But now consider this:
# in one place
a = Stat.aggregated
#in other place
if a.size > 0
'do stuff'
else
'do other stuff'
end
And it works fine if a
relation is loaded, but when a
is not loaded it fails with method undefined
error.
It turns out that when relation is not loaded size calls count
on that relation, which essentially changes the query, returns a hash, and brakes the code.
Is it an implied behavior?
For me it is kind of counter-intuitive to change method semantics depending on whether relation was loaded or not.