How to Determine if Rails Association is Eager Loaded?
association_cached?
might be a good fit:
item.association_cached?(:shipping_infos)
item.shipping_infos.loaded?
will tell you.
I gotta say, though: this path leads to madness... before writing code that tests loaded?
to decide between #detect
and #find
, make sure this instance really matters, relative to everything else that's going on.
If this isn't the slowest thing your app does, adding extra code paths adds unnecessary complexity. Just because you might waste a little database effort doesn't mean you need to fix it - it probably doesn't matter in any measurable way.
I'd suggest using item.association_cache.keys that will provide a list of the eager loaded associations. So you item.association_cache.keys.include?(:name_of_association)
Use .association(name).loaded?
on a record.
For Rails < 3.1 use loaded_foo?
.
(It is deprecated since Rails 3.1. See: https://github.com/rails/rails/issues/472.)