最小化查询数

时间:2011-09-14 03:49:14

标签: ruby-on-rails activerecord

我目前有这个:

data = []

products.each do |product|
  categories = product.shop_categories.select("shop_categories.id, shop_categories.name").map do |category|
  {
    :name => category.name,
    :category_id => category.id.to_s
  }
  end

  data << {
   :name => product.name,
   :product_id => product.productid,
   :manufacturer => product.manufacturer,
   :detail => product.description,
   :categories => categories,
   :sales_rank => product.sales_rank,
   :sale_price => product.sale_price.to_f,
   :price => product.price.to_f,
   :images => product.images,
   :url => product.url,
   :is_rated => current_user.voted_for?(product),
   :is_liked => current_user.voted_as_when_voted(product),
   :is_in_wishlist => current_user.has_product_in_wishlist?(product)
  }
end

在搜索产品“shop_categories时,搜索产品shop_categories的这一部分需要花费大量时间来查询每个产品(每次运行100次)。

有没有办法最小化查询次数或至少最小化此过程耗尽的CPU?

1 个答案:

答案 0 :(得分:1)

使用includes急切加载关联:

data = Product.includes(:shop_categories).collect do |product|
  {
    :name => product.name,
    :product_id => product.productid,
    :manufacturer => product.manufacturer,
    :detail => product.description,
    :categories => product.categories.collect { |c| { :name => c.name, :category_id => c.id.to_s } },
    :sales_rank => product.sales_rank,
    :sale_price => product.sale_price.to_f,
    :price => product.price.to_f,
    :images => product.images,
    :url => product.url,
    :is_rated => current_user.voted_for?(product),
    :is_liked => current_user.voted_as_when_voted(product),
    :is_in_wishlist => current_user.has_product_in_wishlist?(product)
  }
end