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

后端 未结 2 797
死守一世寂寞
死守一世寂寞 2021-02-18 15:11

I can\'t figure out how to user the .where() method to retrieve associated model data. In this example, Projects belongs_to Users...

class Project &         


        
相关标签:
2条回答
  • 2021-02-18 15:24

    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.

    0 讨论(0)
  • 2021-02-18 15:48

    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, ....]}]
    
    0 讨论(0)
提交回复
热议问题