2016-01-22 53 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变量。 –