我有以下設置: 公司的has_many:位置 位置belongs_to的:公司Rails的.includes沒有返回關聯
當我打電話Company.includes(:位置),我得到公司返回,但沒有關聯的地點。
任何想法感謝!
我有以下設置: 公司的has_many:位置 位置belongs_to的:公司Rails的.includes沒有返回關聯
當我打電話Company.includes(:位置),我得到公司返回,但沒有關聯的地點。
任何想法感謝!
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
請注意,您可以使用任何迭代器。我用'收集'只是爲了闡述。謝謝
我不知道你正在嘗試與一家公司做的,但如果你想一個公司,它是你通常會做的地點如下:
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
我試圖從我的查詢返回數據作爲JSON發送到這個問題。
@companies = Company.includes(:locations) render :json => @companies.to_json(:include => [:locations])
爲我工作:)
如果你只是抓取一個單一的公司,並希望加載它的位置,你不需要使用'includes'。執行@company = Company.find(params [:id])'後跟@ @ company.locations'將執行與@company = Company.includes(:locations).find(params [:id])一樣多的查詢' –