The mysteries of size, length and count

ActiveRecord Association and ActiveRecord NamedScope have subtle differences in the way they respond to size, length and count (based on whether records are eager loaded or not) that sometimes leads to some weird results and one can easily land up spending some time debugging these issues.

For more details on this behaviour see 

http://www.wuputah.com/2010/05/24/count-size-and-length-associations-vs-named-scopes/

http://blog.hasmanythrough.com/2008/2/27/count-length-size

So when you want the actual count always call the .all method or do an explicit reload and then call any of the three methods. It helps rely on Array or the collection of reloaded results to give the right result rather than interfering with eager loading, unsaved records and other such stuff. 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s