Ruby on rails 保存表单并检查它是否已存在

Ruby on rails 保存表单并检查它是否已存在,ruby-on-rails,Ruby On Rails,我有一种将产品添加到购物车的方法。现在,每个产品都可以具有产品属性。基本上,我想检查是否已将具有相同属性的产品添加到购物车中。如果是这样的话,我想把数量增加1。如果没有,我想将该产品及其属性添加到购物车中 这里的重要因素是,我需要检查具有相同id的产品的行项目属性,以查看它们的属性是否匹配 def add_product(product_id, instruction, attributes) values = attributes.values attribute_valu

我有一种将产品添加到
购物车的方法。现在,每个产品都可以具有
产品属性
。基本上,我想检查是否已将具有相同属性的产品添加到购物车中。如果是这样的话,我想把数量增加1。如果没有,我想将该产品及其属性添加到购物车中

这里的重要因素是,我需要检查具有相同id的产品的
行项目属性
,以查看它们的属性是否匹配

  def add_product(product_id, instruction, attributes)
    values = attributes.values
    attribute_values = values.map { |attribute| attribute[:product_attribute_id].to_i }.compact

    similar_items = line_items.where(product_id: product_id)

    similar_items.each do |item|
      if item.line_item_attributes.map(&:product_attribute_id).sort == attribute_values.sort
        item.quantity += 1
      end
    end

  end
这就是我到目前为止得到的,属性本质上是如下所示的散列:

{"0"=>{"product_attribute_id"=>"4"}, "1"=>{"product_attribute_id"=>"7"}}
现在,如果我尝试使用“创建”操作保存此文件,则会出现以下错误:

undefined method `save' for []:Array
这是我的控制器创建操作

 def create
    product = Product.find(params[:line_item][:product_id])
    instruction = params[:line_item][:instruction]
    attributes = params[:line_item][:line_item_attributes_attributes].to_unsafe_h

    @line_item = @cart.add_product(product.id, instruction, attributes)
    respond_to do |format|
      if @line_item.save
        format.html { redirect_to store_url(product.store), notice: 'Line item was successfully created.' }
        format.js { @current_item = @line_item }
        format.json { render :show, status: :created, location: @line_item }
      else
        format.html { render :new }
        format.json { render json: @line_item.errors, status: :unprocessable_entity }
      end
    end
  end

Ruby具有隐式回报。这意味着方法中的最后一个对象将是返回值。方法中的最后一个对象是一个可枚举(each),其返回值是迭代的集合。因为where返回数组,所以使用add_product方法返回数组