私は、動的ファインダによって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の数量がいつ更新されたかについての考えはありますか?
line_items.detectは完全に動作します。ありがとう。 –
喜んで助けてください。あなたの問題を解決するならば、答えを受け入れるようにしてください(そして必要に応じてそれをupvoteしてください)。 – Brandan