给定一组埋藏的ID有效找到?

时间:2011-08-13 11:28:40

标签: ruby-on-rails ruby

我有四张桌子,

Shops
Sales
Batches
Products

我希望在召回的情况下提取商店出售的所有产品(批次编号)(同一类型的多个产品可以属于同一批次)。

我的不完整代码看起来像这样......

# GET /shop/1/batches
# GET /shop/1/batches.xml
def batches

  # Obtain unique batches by searching all sales transactions, looking for unique
  # batch IDs.

  @sales = Sales.find_all_by_shop_id(params[:id], :group => :batch_id)

  # I want to avoid doing an iteration over sales.
  # I'd now like to do something like...
  # @batches = Batches.find_all_by_id(@sales.batch_id, :include => [:product])
  # ...to find the set of batches     ^^^^^^^^^^^^^^^
  #
  # 


  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @batches.to_xml(:include => [:product], :except => [:created_at, :updated_at]) }
  end
end

我可以遍历@sales,并从每个中提取product_id以检索产品详细信息,但这会导致许多数据库访问,我不禁想到Ruby / Rails有更好的方法来做到这一点。

1 个答案:

答案 0 :(得分:1)

我猜测销售和批次之间存在belongs_to,您可以通过在find方法中执行包含来实现。它看起来像这样:

@sales = Sales.find_all_by_shop_id(params[:id], :include => :batch)

这将加载符合您条件的所有销售,并且还将仅使用两个SQL语句加载所有相关批次,一个用于销售,另一个用于批次,然后您可以安全地执行 sale.batch 并访问批处理对象。