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
,但由於某種原因,這似乎並沒有工作
什麼是'current_item'?循環中的那行代碼會多次運行,所以它只能有效地使用上次迭代中的'value',是您的意圖嗎? –
@SunilD。我已經更新了我的答案,以包含整個代碼位。 –