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

后端 未结 2 799
死守一世寂寞
死守一世寂寞 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: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, ....]}]
    

提交回复
热议问题