On Tuesday, May 12, 2015 at 4:42:46 PM UTC-7, Janko Marohnić wrote:
>
> A question related to this situation, which I'm not sure it's a bug.
>
> user = User.eager(:quizzes => :questions).all.first
> user.associations #=> {:quizzes => [...]}
>
> user = User.eager(:quizzes => :questions).first
> user.associations #=> {}
>
> So, when I fetch the first user directly, the eager loading is cancelled, 
> meaning that fetching questions for each quiz will result in a N+1 query. 
> However, doesn't Sequel have all the necessary information to do the eager 
> loading?
>

First, if you are loading a single record, there is no reason to use eager 
loading.  Eager loading is only an advantage if you are loading multiple 
records. 1+1 = N+1 if N = 1.

In terms of having the necessary information to eager load, not really. 
 Dataset#first calls Dataset#each, which iterates over the recordset, and 
therefore doesn't have all records available before iterating, which is 
necessary to eager load correctly.  If you want, you can use the eager_each 
plugin, which makes #each call #all internally if the dataset is supposed 
to eager load.

So no, this isn't a bug, it is expected behavior.

If you want to always eager load questions when loading quizzes for a given 
user:

  User.first.quizzes{|ds| ds.eager(:questions)}
  # or
  User.one_to_many :quizzes, :eager=>:questions
  User.first.quizzes # eager loads questions as well

Thanks,
Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.

Reply via email to