76

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.

Adam Lassek
  • 35,156
  • 14
  • 91
  • 107
wbharding
  • 4,213
  • 2
  • 30
  • 25

7 Answers7

85

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

vmarquet
  • 2,384
  • 3
  • 25
  • 39
gamov
  • 3,789
  • 1
  • 31
  • 28
71

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.

ABMagil
  • 4,579
  • 4
  • 21
  • 35
Bryan Stearns
  • 1,297
  • 12
  • 13
  • Thanks Bryan. I understand where you're coming from. This particular code happens to be in the most frequently called partial in our entire app, though, so shaving off even microseconds makes a measurable difference. I'll give #loaded? a try. – wbharding Sep 04 '09 at 06:49
  • 13
    This will only work for has_many associations! In case of belongs_to this call will actually load the other object (so it will be always true) – reto Oct 16 '09 at 12:02
  • 4
    @reto to check for this in `has_one`/`belongs_to` associations you can do `item.association(:shipping_info).loaded?` which works similarly. Added examples and more detail in my answer here: https://stackoverflow.com/a/69349863/1454001 – Jay El-Kaake Sep 27 '21 at 16:10
  • good point, although 12 years too late! :D – reto Sep 27 '21 at 20:34
26

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)

23tux
  • 14,104
  • 15
  • 88
  • 187
dabobert
  • 919
  • 12
  • 10
  • 1
    Perfect solution. Dabogert you're the king :) – Benjamin Bouchet Jan 30 '14 at 23:41
  • 1
    Wow, can't believe that I had been missing this. This works for cases where the association is NOT loaded, but there IS an in-memory cache (e.g. when you build object using the association). – Wizard of Ogz Aug 04 '14 at 13:27
  • 6
    This syntax no longer works in rails 5 (not sure when it changed). It's now `item.association_cached? :name_of_association`. – mpoisot Oct 01 '19 at 17:21
14

association_cached? might be a good fit:

item.association_cached?(:shipping_infos)
phil pirozhkov
  • 4,740
  • 2
  • 33
  • 40
3

Solution to this problem should be foo.association(:bla).loaded?, BUT it works incorrectly - it checks and marks association as dirty:

class Foo; has_one :bla, :autosave => true end
foo.association(:bla).loaded? #=> false
foo.save # saves foo and fires select * from bla

So I've added following extension to ActiveRecord:

module ActiveRecord
  class Base
    def association_loaded?(name)
      association_instance_get(name).present?
    end
  end
end

and now:

class Foo; has_one :bla, :autosave => true end
foo.association_loaded?(:bla) #=> false
foo.save # saves foo
Lev Lukomsky
  • 6,346
  • 4
  • 34
  • 24
  • You should double check that this is still a problem and update the answer to scope it to the appropriate Rails versions. I was unable to reproduce. – Adam Lassek Aug 21 '15 at 21:26
  • Still a problem as of Rails 4.2.6. Not sure if Rails 5 has it. – Omnilord Aug 13 '16 at 15:29
  • What's the consequence of marking it as dirty? Just one extra select statement? Or is there more harm to it? – lulalala Oct 25 '16 at 02:59
  • The consequence of the relation being marked incorrectly as dirty is that rails normally no-ops save calls on models that have no dirty attributes. So you will introduce extra saves and if you're using rails timestamps on the model it'll cause the updated_at times to update when no attributes in the model were actually changed. – jhulford Jan 28 '19 at 16:58
3

You can detect whether or not a single association has been loaded with loaded_foo?. For example, if shipping_info was a belongs_to association, then item.loaded_shipping_info? will return true when it's been eager-loaded. Oddly, it appears to return nil (rather than false) when it hasn't been loaded (in Rails 2.3.10 anyway).

Jim Stewart
  • 16,964
  • 5
  • 69
  • 89
1

Have a look at the Bullet gem.. This will tell you when you should and should not use eager loading.

Ranhiru Jude Cooray
  • 19,542
  • 20
  • 83
  • 128
Bitterzoet
  • 2,752
  • 20
  • 14