before_create仍然保存

Ale*_*jal 3 ruby-on-rails self update-attributes

在此之前,我想感谢你的帮助

我有这样的模型:

  attr_protected nil
  belongs_to :product
  belongs_to :user
  before_create :add_ammount

  def carted_product_price(ammount, price)
    ammount * price
  end

  def add_ammount
    carted_product = CartedProduct.where(:product_id => self.product_id, :user_id => self.user_id)
    if carted_product
      carted_product.first.ammount += self.ammount
      carted_product.first.update_attributes(:ammount => carted_product.first.ammount)
    else
      self.save
    end
  end
Run Code Online (Sandbox Code Playgroud)

它将购买订单保存在名为Carted_Products的表中,该表连接到belogings中的用户和产品

问题是,当Before create执行时,我希望它更新表中的记录,添加控制器传递的ammount,如果记录已经存在,如果没有,创建一个,就iv完成,它更新ammount但是STILL使用顺序中传递的参数创建一个新的,我希望它只更新,而不是在找到记录时执行这两个操作

thnx耐心等待

编辑:

尝试在更新属性后返回false,它取消过滤器,并且不创建或更新属性

mog*_*rod 5

返回falsebefore_create过滤器,以防止被保存对象的形式.add_amount不负责保存对象,也不应该单独调用save.