开发者

Efficient find given a set of buried ids?

I have four tables,

Shops
Sales
Batches
Products

and I would like to extract all the products that have been sold by a shop based on Batch numbers in case of a recall (multiple product items of the same type can belong to the same batch).

My incomplete code looks like this...

# 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 fin开发者_StackOverflowd 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

I could iterate through @sales, and extract the product_id from each to retrieve the product details, but that would result in many database accesses, and I can't help thinking that Ruby / Rails has a better way to do that.


I am guessing there is a belongs_to between sales and batches, you do that by doing an include in your find method. It would look like this:

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

This will load all sales that match your criteria and will also load all related batches with only two SQL statements, one for the sales and another one for the batches and then you can safely do sale.batch and access the batch object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜