gpt4 book ai didi

ruby-on-rails - before_create 仍然保存

转载 作者:行者123 更新时间:2023-12-01 07:39:10 25 4
gpt4 key购买 nike

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

我有这样一个模型:

  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 中的用户和产品

问题是,当 Before create 执行时,我希望它更新表中的记录,如果记录已经存在,则添加 Controller 传递的 ammount,如果不存在,则创建一个,到目前为止正如 iv 所做的那样,它更新了 ammount 但仍然按顺序创建一个包含传递的参数的新的,我希望它只更新,而不是在找到记录时执行这两个操作

谢谢你的耐心

编辑:

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

最佳答案

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

关于ruby-on-rails - before_create 仍然保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11572007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com