Rails .includes 不返回关联

Rails .includes not returning association

我有以下设置: 公司 has_many :地点 地点belongs_to:公司

当我调用 Company.includes(:locations) 时,我得到了返回的公司,但是 none 个相关位置。

欢迎任何想法!

我不确定您要对一家公司做什么,但如果您想要一家公司及其所在地,您通常会执行以下操作:

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

的列表

预加载是必要的,因为它可以优化您的应用程序的性能并防止您的系统 运行 进入 N+1 查询问题。假设您的数据库中有 3000 家公司,那么您的数据库将充满 3000+1 个查询。所以在控制器中你可以把它实现为

@companies = Company.includes(:locations)

同样对于单个公司,您可以这样做

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

现在会预先加载位置,您可以将它们作为

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

@company.locations

Note you can use any iterator. I used 'collect' just for the purpose of elaboration. Thanks

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

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

对我有用:)