TODAY I LEARNED

How to check if an ActiveRecord association was already eager loaded

if you need to know whether to use a pre-laoded collection using eager loading or fech the collections, you can always call loaded? method:

if user.contact_phones.loaded?
  user.contact_phones.detect? {|phone| phone.primary }
else
  user.contact_phones.find_by(primary: true)
end

Tweet

Learned by Edwin Cruz on Apr 19, 2021

Discover our latest blog posts
  • #rails
  • view raw
  • permalink
  • 2 likes
previous TIL next TIL
  • Log in
  • ?

    TIL is an open-source project by MagmaLabs that exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any MagmaLaber as well as selected friends of MagmaLabs. We hope you enjoy learning along with us.

    • /wearemagmalabs
  • statistics
  • search
  • Twitter