It was so simple: user.associations[:quizzes] = user.quizzes_dataset.eager(:questions).all
I'm so happy Sequel is so simple. I wouldn't be able to do this with ActiveRecord, because ActiveRecord for some reason stores association *reflections* in its #association_cache, then you have to call #traget on it to get the actual preloaded records (I have no idea how would I populate it manually then). With Sequel it's just so much easier to do these advanced things. On Tuesday, May 12, 2015 at 10:14:28 PM UTC+2, Janko Marohnić wrote: > > Hi Jeremy, > > When I have an already instantiated Sequel model, is it possible to apply > cascaded eager loaded associations? For example, if I have > > class User < Sequel::Model > one_to_many :quizzes > end > > class Quiz < Sequel::Model > one_to_many :questions > end > > class Question < Sequel::Model > end > > Is it possible to make it that `user.quizzes.map(&:questions)` executes > only one query for questions (that questions are eager loaded). I need this > because when I'm returning a single record, any previous eager loading are > canceled. That is, the following > > User.eager(:quizzes => :questions).first.quizzes.map(&:questions) > > Will separately fetch questions for each quiz, even though I eager loaded > them. The reason why I can't just call > `user.quizzes_dataset.eager(:questions)` is because when I'm serializing > that user for a JSON response, the serializer will automatically serialize > the `user.quizzes.questions` association, by calling the association > methods directly. So, the serializer would have to somehow know not to call > `user.quizzes`, but `user.quizzes_dataset.eager(:questions).all`, which I > don't know how to implement without some nasty special case. > > So, I would like to somehow on the instance level cause the method > `user.quizzes` to automatically return quizzes with eager loaded questions. > -- 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.
