拒绝记录保存而不会引发错误

时间:2019-08-30 05:09:36

标签: ruby-on-rails ruby ruby-on-rails-5

我正在运行Rails 5.2。我有一个CartItem模型,我想合并添加到购物车中的重复items的数量和总数。

我的Cart接受Item的嵌套属性,我最初考虑使用reject_if条件来防止保存“重复的” item。但是,实际上我需要从模型中执行此操作,因为我还有其他脚本可以创建购物车和商品,而无需向控制器提交表单数据。从Item模型的回调中,如何像使用reject_if那样拒绝保存?

我放弃的最初想法:

class Cart < ApplicationRecord
    has_many :items
    accepts_nested_attributes_for :items, reject_if: proc { |attributes| attributes.function_that_decides_to_reject_or_not }
end

我想要实现的目标:

class Item < ApplicationRecord
    belongs_to :cart
    before_save :combine_and_reject

    def combine_and_reject
        #pseudo-code
        #if self.sku == to other items' sku in cart
            #combine the quantities and reject self silently. 
        #end
    end
end

先谢谢了。

1 个答案:

答案 0 :(得分:1)

也许我错过了一些东西,但我不明白为什么要在模型中处理这个问题。我建议您在显示Cart时“即时”计算。想象以下代码:

#carts controller

def show
  skus = @cart.items.pluck(:sku)
  # ['678TYU', '678TYU', 'POPO90']
  skus.each_with_object(Hash.new(0)) { |sku,counts| counts[sky] += 1 }
  # {"678TYU"=>2, "POPO90"=>1}
end

通过这种方式,每次您要显示购物车时,都可以根据重复项来处理数量。

购物车中的重复不是问题,因为在现实生活中,购物车中可以有两个巧克力棒。只有在收据上,重复项才会消失。

相关问题