Thursday, January 21, 2010

[Rails] 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

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate