method

includes

includes(*args)
public

Specify relationships to be included in the result set. For example:

users = User.includes(:address)
users.each do |user|
  user.address.city
end

allows you to access the address attribute of the User model without firing an additional query. This will often result in a performance improvement over a simple join.

You can also specify multiple relationships, like this:

users = User.includes(:address, :friends)

Loading nested relationships is possible using a Hash:

users = User.includes(:address, friends: [:address, :followers])

conditions

If you want to add string conditions to your included models, you’ll have to explicitly reference them. For example:

User.includes(:posts).where('posts.name = ?', 'example')

Will throw an error, but this will work:

User.includes(:posts).where('posts.name = ?', 'example').references(:posts)

Note that #includes works with association names while #references needs the actual table name.

If you pass the conditions via hash, you don’t need to call #references explicitly, as #where references the tables for you. For example, this will work correctly:

User.includes(:posts).where(posts: { name: 'example' })

1Note

Links and basic explanation

dancinglightning · Jan 2, 20123 thanks

This function, available on any Base derived class, allows eager loading. So when iterating over a result, all the data can be pre-cached, reducing the number of queries from 1+x to 2.

Several ways to use this include:

Post.includes(:author).where(..)

Post.includes([:author, :comments]).where(..)

Post.includes( :comments => :replies ).where(..)

The result is a Relation, so where and other function may be called.

.includes(:comments).to_a is the same as , .find(:all, :includes => :comments)

Some good documentation here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Apperently one can get similar results by using joins, but i'm not expert on joins, so please ammend and read: http://guides.rubyonrails.org/active_record_querying.html