2012-03-20 8 views
0

私は、動的ファインダによってhas_manyコレクションからオブジェクトを見つけようとしています。しかし、更新された属性値がいつ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の量はまだupdaing前の値です。ただし、次にLineItemsController.createを呼び出すと、カート内のline_itemの数が更新されます。 カート内のline_itemの数量がいつ更新されたかについての考えはありますか?

答えて

0

個別の広告申込情報を更新した後、最も簡単な解決策はcart.line_items(true)です。これにより、Railsはアソシエーション全体をデータベースからリロードします。これには、広告申込情報の量の変更が含まれている必要があります。

find_by_product_idの代わりにdetectを使用して、広告申込情報の配列から直接広告申込情報を取得することもできます。これにより、同じオブジェクトを使用していることが保証されますが、最初にデータベースからすべての広告申込情報を読み込む必要があります(既に好きなように思えます)。

current_item = line_items.detect { |item| item.product_id == product_id } 
+0

line_items.detectは完全に動作します。ありがとう。 –

+0

喜んで助けてください。あなたの問題を解決するならば、答えを受け入れるようにしてください(そして必要に応じてそれをupvoteしてください)。 – Brandan

関連する問題