在每个循环中获取has_many关联记录的最快方法



我有一个has_many直通协会,我有许多产品,它们的价格因国家而异(每个国家只能有一个价格(。

我要做的循环是以下

@product.countries.each do |country|
country.name 
# here I want to get the price of this product in that country
end

我想要一些类似country.prices.where(product_id: @product.id).first的东西

我相信有一种干净的方法可以纠正这个代码,而不必使用where。你知道怎么做吗?


这是我的型号

产品

has_many :prices
has_many :countries, through :prices

价格

belongs_to :product
belongs_to :country
belongs_to :currency

国家

has_many :prices
has_many :products, through :prices

您可以将其翻转过来,并像这样处理它们:

@product.prices.each do |price|
price.country.name
# now you already have the price
end

当然,您所在的国家/地区现在的订单可能会不令人满意,对于您显示的每一个价格,您都会触发额外的DB查询。由于价格表很大,这可能很快成为性能问题。

解决方案是创建一个可以使用的范围,或者手动获取价格,而不仅仅是使用裸关联,允许您快速加载相关数据并根据它们订购价格:

# In your controller, or model code somewhere:
@prices = @product.prices.joins(:country).order('countries.name').includes(:country)
# The joins is required for ordering, and the includes ensures you eager-load that data
# In your view:
@prices.each do |price|
price.country.name # Now these should be in the correct order and eager-loaded rather than fetched in ever iteration of this prices loop
# you already have the price to use here
end

最新更新