How to Determine if Rails Association is Eager Loaded?

wbharding picture wbharding · Sep 4, 2009 · Viewed 22.3k times · Source

Does anyone know a way to determine if a Rails association has been eager loaded?

My situation: I have a result set where sometimes one of the associations is eager loaded, and sometimes it isn't. If it isn't eager-loaded, then I want to look up associations using ActiveRecord's find. If it is eager loaded, I want to use detect.

For example, say that I have a "has_many" array of shipping_info objects in my item model. Then:

If item is eager loaded, most efficient load is:

item.shipping_infos.detect { |si| si.region == "United States" }

If item isn't eager loaded, most efficient load is:

item.shipping_infos.where(region: "United States").first

But unless I know whether it is eager loaded, I don't know which code to call to get the record efficiently. If I use the first method when it wasn't eager loaded, then I have to look up more DB records than necessary. And if I use the second method when it was eager loaded, then my eager loaded objects are ignored.

Answer

gamov picture gamov · Jun 7, 2011

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