0

ダイナミックファインダーによってhas_manyコレクションからオブジェクトを検索し、返されたオブジェクトの属性を更新しようとしています。しかし、更新された属性値がいつhas_manyコレクションに同期されるかは本当にわかりません。返されたオブジェクトは、has_manyコレクション内のどのオブジェクトとも異なる新しいオブジェクトであることがわかったためです。

class Cart < ActiveRecord::Base
  has_many :line_items, :dependent => destroy

  def add_product(product_id)
    current_item = line_items.find_by_product_id(product_id) 
    #here current_item is #<LineItem:0x007fb1992259c8>
    #but the line_item in has_many collection line_items is #<LineItem:0x007fb19921ed58>
    if current_item
      current_item.quantity += 1
    else
      current_item = line_items.build(:product_id => product_id)
    end
    current_item
  end
...
end

class LineItemsController < ApplicationController
  ...
  def create
    @cart = current_cart
    product = Product.find(params[:product_id])
    @line_item = @cart.add_product(product_id)

    respond_to do |format|
      if @line_item.save
        format.js { @current_item = @line_item }
      end
    end
  end
  ...
end

current_itemの数量を更新した後、カートをレンダリングすると、カート内のline_itemの数量は更新前の値のままになります。ただし、次にLineItemsController.createを呼び出すときに、カート内のline_itemの数量が更新されました。それで、カート内のline_itemの数量がいつ更新されるかについて何か考えはありますか?

4

1 に答える 1

0

最も簡単な解決策はcart.line_items(true)、個々の広告申込情報を更新した後に電話をかけることです。これにより、Railsはデータベースから関連付け全体を再読み込みします。これには、広告申込情報の数量の変更が含まれている必要があります。

detect代わりにfind_by_product_id、ラインアイテムの配列からラインアイテムを直接フェッチすることもできます。これにより、同じオブジェクトを使用していることが保証されますが、最初にデータベースからすべてのラインアイテムをロードする必要があります(すでに実行しているように聞こえます)。

current_item = line_items.detect { |item| item.product_id == product_id }
于 2012-03-20T16:07:04.403 に答える