简体   繁体   English

迭代哈希值以保存嵌套属性

[英]iterate on hash of hashes to save nested attribute

I have a hash of hashes that I obtain from the params. 我有一个从参数中获得的哈希值哈希。 Looking like this: 看起来像这样:

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

now essentially what I want to do is something like this: 现在基本上我想做的是这样的:

  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

but for some reason this doesn't seem to work 但由于某种原因,这似乎不起作用

Just fyi, assuming you are using the Rails' build method used in active model associations, build will not save to database. 只是假设您正在使用活动模型关联中使用的Rails的build方法, build不会保存到数据库中。

See http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html It reads: 参见http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html内容如下:

build_association(attributes = {}) Returns a new object of the associated type that has been instantiated with attributes and linked to this object through a foreign key, but has not yet been saved. build_association(attributes = {})返回一个已关联类型的新对象,该对象已用属性实例化并通过外键链接到该对象,但尚未保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM