I have a Rails 5.1 (Ruby 2.4.0) Widget class which has_one foo and has_many bars (both optional).
class Widget < ApplicationRecord
has_one: foo
has_many: bars
# methods
end
I have a method in which I want to eagerly load an array of Widgets with their associated foos/bars, and in looping over the array call a function that examines the foos/bars of each one:
widget_arr= Widget.includes(:foo, :bars).where(#widget_conditions)
widget_arr.each do |widget|
useful_info = widget_resolver_fn(widget)
#purposeful logic using useful_info
end
def widget_resolver_fn(widget)
do_something unless widget.foo.nil?
do_something_else unless widget.bars.empty?
return useful_information
end
I have an n+1 query problem with my bars but not with foos. Reading the rails guides it seems to be related to the fact that for the has_many association it returns a collection proxy, rather than an array of loaded objects.
Looking around Google I've found mentions of includes, eager_load and preload methods- the rails guides tell you nothing about these last two, and I've tried them all without success. (eager_load actually broke the query, and in the absence of documentation I couldn't write one that made the method work). My list of widgets can easily be greater than 100 in length, so I'm quite keen to sort this out.
Thanks in advance for any help.
No responses yet.