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 :/
What is the difference between includes and joins? The most important concept to understand when using includes and joins is they both have their optimal use cases. Includes uses eager loading whereas joins uses lazy loading, both of which are powerful but can easily be abused to reduce or overkill performance.
Rails provides an ActiveRecord method called :includes which loads associated records in advance and limits the number of SQL queries made to the database. This technique is known as "eager loading" and in many cases will improve performance by a significant amount.
The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins).
Active Record. Active Record objects don't specify their attributes directly, but rather infer them from the table definition with which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects.
Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With