Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does :include work on ActiveRecord instances?

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 :/
like image 858
Anthony Bishopric Avatar asked May 08 '11 20:05

Anthony Bishopric


People also ask

What is difference between joins and include in Rails?

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.

What is the use of include in Rails?

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.

What is include in Ruby on Rails?

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).

What is ActiveRecord base?

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.

What's the purpose of ActiveRecord?

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.


1 Answers

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

like image 177
aNoble Avatar answered Sep 20 '22 01:09

aNoble