2016-07-27 70 views
1

我有以下设置: 公司的has_many:位置 位置belongs_to的:公司Rails的.includes没有返回关联

当我打电话Company.includes(:位置),我得到公司返回,但没有关联的地点。

任何想法感谢!

+0

如果你只是抓取一个单一的公司,并希望加载它的位置,你不需要使用'includes'。执行@company = Company.find(params [:id])'后跟@ @ company.locations'将执行与@company = Company.includes(:locations).find(params [:id])一样多的查询' –

回答

1

Eager Loading是必要的,因为它可以优化应用程序的性能并防止系统运行到N + 1查询问题。假设你的数据库中有3000家公司,那么你的数据库将被3000 + 1个查询充斥。因此,在控制器就可以实现它作为

@companies = Company.includes(:locations) 

同样,对于一个公司,你可以做到这一点作为

@company = Company.includes(:locations).find(params[:id]) 

现在的位置会被即时加载,你可以为

@companies.collect{ |company| company.locations } 
获取它们

@company.locations 

请注意,您可以使用任何迭代器。我用'收集'只是为了阐述。谢谢

1

我不知道你正在尝试与一家公司做的,但如果你想一个公司,它是你通常会做的地点如下:

class Company 
    has_many :locations 
end 

class Location 
    belongs_to :company 
end 

class CompaniesController < ApplicationController 
    def show 
    @company = Company.find(params[:id]) 
    @locations = @company.locations 
    end 
end 

然后在你的show视图,你会请拨打@locations.each do |location|以遍历列表locations

0

我试图从我的查询返回数据作为JSON发送到这个问题。

@companies = Company.includes(:locations) render :json => @companies.to_json(:include => [:locations])

为我工作:)