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

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -