Frederick Cheung wrote:
> On Aug 3, 5:40�pm, Mark Ron <rails-mailing-l...@andreas-s.net> wrote:
> 
>> Why doesn't it use the include? method of the Array? (way faster and
>> doesn't need db queries at all, since the association is already
>> loaded.) Why does it need its own include? method?
> 
> Presumably the association isn't actually loaded - the code in
> association_collection.rb checks for that and uses Array#include? if
> the association is loaded (at least that is the intent).
> 
> The key thing is that active record doesn't know ahead of time if you
> are going to do this once (in which case loading 1000 objects just to
> do this test would be wasteful) or if you are going to loop over a
> long list of products in which case not loading the array is
> wasteful). You can however (as you have found) force AR to go down the
> more efficient route (but yes, it would be nicer if it was better at
> guessing what you wanted to do).
> 
> Fred

so basically it's the same 1+N query problem we face when we try to 
access attributes of an associated object when we iterate through the 
collection of the parent. but that one does have a solution, if you 
include the associated model in the original query. (eager loading 
associations)

for post in Post.find(:all, :include => :author) # 2 db queries)
  p post.author.name #no db query
end


but in  case of object.collections, AR caches the association 
automatically like:

project.milestones             # fetches milestones from the database
project.milestones.size        # uses the milestone cache
project.milestones.empty?      # uses the milestone cache
project.milestones(true).size  # fetches milestones from the database
project.milestones             # uses the milestone cache

So technically AR should know that the associated objects are loaded 
already (and cached) so the include? method should use the faster 
Array#include? method instead of AssociationCollection#inlcude? or to be 
more accurate #exists? method, right?

project.milestones.include?(milestone) #should be fetched from cache 
too, no db query should be needed)

It seems that it's programmed in the framework, but for some reason in 
my example it's always getting the result from the database instead of 
the already loaded association cache.

Why is that?

Thanks,
Mark

-- 
Posted via http://www.ruby-forum.com/.

--~--~---------~--~----~------------~-------~--~----~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to