Is an association already loaded?

If you can’t tell… I like posting little “cheatsheet” items here. So, here’s another one that I’ve bumped into again recently after not needing it for a while.

You want to know how many Items are currently in the Store and you’ve got this in your Store definition:
has_many :items

If the Items for this Store have already been read in and objects have been mapped, you simply want to ask for the count:
flagship_store.items.size

but if they haven’t already been mapped, you want to just do a quick select count(*):
Item.count(:conditions => ["store_id = ?", flagship_store.id])

The answer?

For many of us it’s:

item_count = flagship_store.instance_variable_get(:@items) ? @items.size : Item.count(:conditions => ["store_id = ?", flagship_store.id])

And for those of you living in the future it’s even more straightforward:

item_count = flagship_store.instance_variable_defined?(:@items) ? @items.size : Item.count(:conditions => ["store_id = ?", flagship_store.id])

Advertisements

Leave a comment

Filed under rails

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s