includes(*args) public

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

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

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


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

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

Will throw an error, but this will work:

User.includes(:posts).where(' = ?', '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' })
Show source
Register or log in to add new notes.