2016-01-22 55 views
1

我有一個散列哈希,我從參數中獲得。這樣看:散列哈希迭代保存嵌套屬性

{"0"=>{"product_attribute_id"=>"4"}, "1"=>{"product_attribute_id"=>"7"}} 

現在基本上就是我想要做的是這樣的:

class Cart < ApplicationRecord 
    has_many :line_items, dependent: :destroy 

    def add_product(product_id, instruction, attributes) 
    current_item = line_items.find_by(product_id: product_id) 
    if current_item 
     current_item.quantity += 1 
    else 
     current_item = line_items.build(product_id: product_id, instruction: instruction) 
     attributes.each do |key, value| 
     current_item.line_item_attributes.build(product_attribute_id: value['product_attribute_id']) 
     end 
    end 
    current_item 
    end 

,但由於某種原因,這似乎並沒有工作

+0

什麼是'current_item'?循環中的那行代碼會多次運行,所以它只能有效地使用上次迭代中的'value',是您的意圖嗎? –

+0

@SunilD。我已經更新了我的答案,以包含整個代碼位。 –

回答

0

僅供參考,假設你正在使用Rails的build方法用於活動模型關聯,build不會保存到數據庫。

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html 它讀取:

build_association(屬性= {})返回已實例化的屬性,並通過外鍵鏈接 到該對象的 相關類型的新對象,但尚未保存。

+0

嗯,我不完全知道它做了什麼。它似乎適用於我擁有的current_item變量。 –