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。我已经更新了我的答案,以包含整个代码位。 –