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 回答