How to Determine if Rails Association is Eager Loaded?

前端 未结 7 1287
后悔当初
后悔当初 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:47

    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
    
    0 讨论(0)
提交回复
热议问题