2016-01-22 57 views
0

我有一個將產品添加到cart的方法。現在每個產品都可以有product_attributes。基本上我想要的是檢查具有相同屬性的產品是否已添加到購物車。如果是這樣,我想通過1.增加的數量如果沒有,我想補充一點的產品與它的屬性到購物車。保存表單並檢查是否存在已

這裏最重要的因素是,我需要檢查line_item_attributes產品具有相同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 

回答

0

Ruby有隱含的回報。這意味着方法中的最後一個對象將是返回值。在方法的最後一個對象是一個枚舉(每個)的返回值是被遍歷集合。由於where返回數組,所以您使用add_product方法返回一個數組。