Ruby on rails 包括不返回关联

Ruby on rails 包括不返回关联,ruby-on-rails,activerecord,include,associations,Ruby On Rails,Activerecord,Include,Associations,我有以下设置: 这家公司有很多地点 地点所属:公司 当我打电话给Company.includes(:locations)时,我会返回公司,但没有相关的位置 任何想法都很感激 我不确定你想对一家公司做什么,但如果你想要一家公司,并且它位于不同的地点,你通常会做以下事情: class Company has_many :locations end class Location belongs_to :company end class CompaniesController <

我有以下设置: 这家公司有很多地点 地点所属:公司

当我打电话给Company.includes(:locations)时,我会返回公司,但没有相关的位置


任何想法都很感激

我不确定你想对一家公司做什么,但如果你想要一家公司,并且它位于不同的地点,你通常会做以下事情:

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
class公司
有很多:地点
结束
类位置
属于:公司
结束
类CompaniesController

然后在
show
视图中,调用
@locations.each do | location |
,以迭代
位置列表

紧急加载是必要的,因为它优化了应用程序的性能,并防止系统出现N+1查询问题。假设您的数据库中有3000家公司,那么您的数据库将充满3000+1查询。因此,在控制器中,您可以将其实现为

@companies = Company.includes(:locations)
同样,对于单个公司,您也可以按如下方式进行操作:

@company = Company.includes(:locations).find(params[:id])
现在,位置将被急切地加载,您可以按如下方式获取它们

@companies.collect{ |company| company.locations }

注意,您可以使用任何迭代器。我使用“收集”只是为了详细说明。谢谢


我在尝试将查询中的数据作为JSON发送回时遇到了这个问题

@companys=Company.包括(:位置)
render:json=>@companys.to_json(:include=>[:locations])


为我工作:)

如果您只是获取一家公司并希望加载其位置,则不需要使用
包含
。执行@company=company.find(params[:id])`后接
@company.locations
将执行与
@company=company.includes(:locations).find(params[:id])
@company.locations