I'm trying to find a object from the has_many collection by dynamic-finders, and then update the attribute of the returned object. But I really don't know when the updated attribute value will be synchronized to the has_many collection. Because I found the returned object is a new object different from any of the objects in the has_many collection.
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
After updating the quantity of current_item, when render the Cart, the quantity of the line_item in the cart still be the value before updaing. But however, the next time when calling LineItemsController.create, the quantity of the line_item in the cart has been updated. So is there any idea about when the quantity of the line_item in the cart been updated?