before_create 仍然保存 [英] before_create still saves

查看:53
本文介绍了before_create 仍然保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此之前,我要感谢您的帮助

Before everything i would like to thank you for your help

我有一个这样的模型:

  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

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

it saves buying orders in a table called Carted_Products connected to Users and Products in the belogings

问题是,当 Before create 执行时,我希望它更新表中的记录,如果记录已经存在,则添加控制器传递的数量,如果不存在,则创建一个,到目前为止iv 完成后,它更新了数量,但仍按顺序使用传递的参数创建一个新的,我希望它只更新,而不是在找到记录时执行这两个操作

the problem is that when the Before create executes i want it to update the record in the table adding the ammount passed by the controller if the record already exists and if not, create one, as far as iv done, it updates the ammount but STILL CREATES A NEW one with the passed params in the order, i want it only to update, not to do both actions when the record is found

感谢您的耐心

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

Tried returning false after the update attributes, it cancels the filter, and dont create or update attributes

推荐答案

before_create 过滤器中返回 false 以防止对象表单被保存.add_amount 不负责保存对象,不应自行调用 save.

Return false in the before_create filter to prevent the object form being saved. add_amount is not responsible for saving the object, and shouldn't call save by itself.

这篇关于before_create 仍然保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆