Rails 4: How to use includes() with where() to retrieve associated objects Rails 4: How to use includes() with where() to retrieve associated objects ruby ruby

Rails 4: How to use includes() with where() to retrieve associated objects


The user object is not part of the project object, so you won't be able to view it on the project: rather, by saying Project.includes(:user), you're telling Rails to eager-load the referenced association when it finds the project. This saves you a database call down the road. For example, non-eagerly:

@project = Project.where(id: params[:id]).first # one database call, fetching the project@project.user # another database call, fetching the user

And eagerly:

@project = Project.includes(:user).where(id: params[:id]).first # one database call, fetching both project and user@project.user # no database interaction

This matters more with has_many queries where eager-loading associations can save N+1 database queries.

You can verify this is working appropriately by calling @project.user at some point after the eager load and checking your logs: you should see that there was no database call at that point.


Eager loading, N+1 query optimization is really an efficient way of loading associations in a single call.

- includes() with where() and find()

@project = Project.includes(:user).where(hashed_id: params[:id]).first@project = Project.where(hashed_id: params[:id]).includes(:user).first

* In some cases, It can be useful*

@projects = Project.find(:all, :includes => :user)@projects = Project.find(:all, :include => [{:association1 => [:associationA, :associationB, ....]}]