Forcing load_target

Hi,
I have the case where I have an object A, which has a has_many through
relationship with objects B. Each A will be associated with a
relatively small number of Bs. I want to cycle through some Bs, and
check if an A has them.

So, something like:
a = A.find 123
bs = B.all
bs.map{|b| a.list_of_bs.include? b}

The problem is that in this case, while it would be more efficient to
load all the Bs at once, ActiveRecord will, for each, do something
like

SELECT Bs.id FROM Bs INNER JOIN As_Bs ON Bs.id = As_Bs.B_id where
Bs.id = 1 AND As_Bs.B_id = 123 LIMIT 1

This would make sense if I could have an arbitrary number of Bs
associated with an A, but for my use case, loading all Bs for the A is
more efficient. load_target in association_base does this, but is
protected. Currently, I’m doing something like a.list_of_bs.length
before everything else, which triggers load_target, but this seems
less than ideal. Is there a standard way to trigger load_target?
Thanks
Rob

Hi,

I’m not sure I’m understanding. Are you asking about eager loading
associations? If that is the case it can be done with :include when
you get you A record.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs