在ruby中从集合构建哈希索引

时间:2015-04-12 16:26:03

标签: ruby-on-rails ruby hash

这是我试图从记录集中获取的内容:

{
  "transaction": {
    "amount":"45.55",
    "currency":"CAD",
  },
  "detail": {
    "0": {
      "sku":"Product_id",
    },
    "1": {
      "sku":"Product_id",
    },
    "2": {
      "sku":"Product_id",
    }
  }
}

我需要遍历订单商品并使用索引构建哈希。

# Order model
order has_many :items, class_name: "LineItem"
Order.column_names
=> ["id", "amount", "currency"]

# LineItem model
LineItem.column_names
=> ["id", "sku", "order_id"]

这是我到目前为止所看到的,但看起来我不能这样做:

{
  transaction: {
    amount: order.subtotal,
    currency: order.currency,
  },
  detail: {
    order.items.each_with_index do |item, index|
      index: {
        sku: item.sku
      }
    end
  }
}.to_json

所以,让我们分别尝试构建嵌套哈希,但也没有运气。

ha = items.each_with_index do |item, index|
       index => Hash.new(sku: item.sku)
     end

1 个答案:

答案 0 :(得分:0)

这是我最终做的事情

body = { 
  transaction: {
    amount:"45.55",
    currency:"CAD",
  }
}

items_hash = {}
items.each_with_index do |item, index|
  h = { "#{index}" => { sku: item.sku } }
  items_hash.merge!(h)
end

details = { "transaction_detail" => items_hash }

hash = hash.merge!(details)
hash.to_json