Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Determine if Rails Association is Eager Loaded?

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.

like image 383
wbharding Avatar asked Sep 03 '09 22:09

wbharding


People also ask

What is Rails eager load?

Eager loading is a way to find objects of a certain class and a number of named associations. Here I share my thoughts on using it with Rails. What are N + 1 queries? It mainly occurs when you load the bunch of objects and then for each object you make one more query to find associated object.


1 Answers

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

like image 91
gamov Avatar answered Oct 18 '22 05:10

gamov