7

All the examples of :include for eager loading are for class-level querying. I tried it on my model instance and it still issued a bunch of queries - does it work on instance methods?

 #in controller
 @emails = person.sent_emails(:include => [:recipient])

 #in view
 render @emails

 # _email.html.erb partial
 <h1><%= email.recipient.name %></h1>
 <p>
 <%= email.content %>
 </p>

 #still issues a select * for emails, N+1 for recipients :/
Anthony Bishopric
  • 1,306
  • 11
  • 23

1 Answers1

3

It looks a bit Rails 2ish I know and there may be a better Rails 3 way but this does work.

@emails = person.sent_emails.find(:all, :include => :recipient)

Edit: See the comment by BaroqueBobcat for a better method in Rails 3

aNoble
  • 7,033
  • 2
  • 37
  • 33
  • 3
    you can use `sent_emails.all(:include => :recipient)` – BaroqueBobcat May 08 '11 at 21:14
  • Used BaroqueBobcat's syntax - that's what I was missing. Thanks – Anthony Bishopric May 08 '11 at 21:16
  • OK, so in this example I have a Person instance. And I can do "person.sent_emails.all(:include => :recipient)". And it returns the result I expected. But the person.sent_emails variable is unchanged. How can I load these associations right inside the ActiveRecord instance? – AndroC May 04 '14 at 11:30