[英]Rails .includes not returning association
I have the following setup: Company has_many :locations Location belongs_to :company 我有以下设置:Company has_many:locations位置belongs_to:company
When I call Company.includes(:locations), I'm getting the company returned back, but none of the associated locations. 当我致电Company.includes(:locations)时,我得到的是公司退回的信息,但是没有一个相关的位置。
Any ideas are appreciated! 任何想法表示赞赏!
I'm not sure what you are trying to do with a company, but if you want one company and it's locations you would generally do the following: 我不确定您要与一家公司做什么,但是如果您想要一家公司及其所在地,通常可以执行以下操作:
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
Then in your show
view, you would call @locations.each do |location|
然后在
show
视图中,您将调用@locations.each do |location|
in order to iterate over the list of locations
为了遍历
locations
列表
Eager Loading is necessary as it optimizes the performance of your application and prevent your system to run into N+1 query problem. 急切加载是必要的,因为它可以优化应用程序的性能并防止系统遇到N + 1查询问题。 Suppose you have 3000 companies in your database then your database will be flooded with 3000+1 queries.
假设您的数据库中有3000家公司,那么您的数据库将充满3000 + 1个查询。 So in the controller you can achieve it as
因此,在控制器中您可以实现为
@companies = Company.includes(:locations)
Similarly for single company you can do it as 同样,对于单个公司,您也可以这样做
@company = Company.includes(:locations).find(params[:id])
Now locations will be eagerly loaded and you can fetch them as 现在,位置信息会急切加载,您可以将其作为
@companies.collect{ |company| company.locations }
OR 要么
@company.locations
Note you can use any iterator.
请注意,您可以使用任何迭代器。 I used 'collect' just for the purpose of elaboration.
我仅出于阐述目的使用“收集”。 Thanks
谢谢
I ran into this problem when trying to send the data from my query back as JSON. 尝试将查询中的数据发送回JSON时遇到了这个问题。
@companies = Company.includes(:locations) render :json => @companies.to_json( :include => [:locations] )
Worked for me :) 为我工作:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.