ruby on rails - ActiveRecord Relation size strange behavior -
i have encountered strange behavior of activerecord relation recently. suppose, have stat
model following properies:
clicks
views
created_at
- and others
further suppose have following scope:
scope :aggregated, select('sum(clicks) clicks, sum(views) views).group('date(created_at)')
as result expect array of stat object info aggregated day, , is. consider this:
# in 1 place = 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, when a
not loaded fails method undefined
error. turns out when relation not loaded size calls count
on relation, changes query, returns hash, , brakes code.
is implied behavior?
for me kind of counter-intuitive change method semantics depending on whether relation loaded or not.
that's how activerecord relation works. can convert array , size on it.
a = stat.aggregated.to_a #in other place if a.size > 0 'do stuff' else 'do other stuff' end
Comments
Post a Comment