How to Determine if Rails Association is Eager Loaded?

前端 未结 7 1292
后悔当初
后悔当初 2021-01-30 16:02

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 l

相关标签:
7条回答
  • 2021-01-30 16:27

    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)

    0 讨论(0)
  • 2021-01-30 16:28

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

    0 讨论(0)
  • 2021-01-30 16:29

    association_cached? might be a good fit:

    item.association_cached?(:shipping_infos)
    
    0 讨论(0)
  • 2021-01-30 16:30

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

    0 讨论(0)
  • 2021-01-30 16:38

    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.

    0 讨论(0)
  • 2021-01-30 16:45

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

    0 讨论(0)
提交回复
热议问题