includes

includes(*args)
Instance Public methods

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

1
2
3
4
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:

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

Loading nested relationships is possible using a Hash:

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

conditions

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

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

Will throw an error, but this will work:

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

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

doc_ruby_on_rails
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.