7
votes

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 :/
1
What is inside the partial _email?Harish Shetty
Added it to the questionAnthony Bishopric
The email.recipient call should run select * from users if the recipient is not eager loaded. Are you sure you are seeing select * from emails multiple times?Harish Shetty
select * from emails happens one time, then does select * from people where id = :recipient_id N timesAnthony Bishopric

1 Answers

3
votes

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