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])