1

我正在尝试将哈希数组数据包含在厨师数据包项中。这支持吗?我不断收到有关未定义方法的错误消息。这是一个例子:

数据包项目:

{
        "id": "BurgerKing",
        "sandwich": "Whopper",
        "nickname": "BK",
        "value_meals":[
                {
                "sandwich":  "Big King",
                "side": "Fries",
                "drink": "Coke"
                },
                {
                "sandwich": "Kids Burger",
                "side": "Apple Slices",
                "drink": "Milk"
                }
        ]
}

模板:

<!-- I want to go to <%= @restaurant[ 'nickname' ] %> to get a <%= @restaurant['sandwich'] %>. -->
<!-- But there are also value meals... -->
<% @restaurant.value_meals.each do | meal | %>
<!-- <%= meal.sandwich %>, <%= meal.side %>, and <%= meal.drink %> -->
<% end -%>

如果我只访问三明治和昵称字段,那就太好了,但是只要我添加代码来遍历 value_meals,我就会得到:

Chef::Mixin::Template::TemplateError (undefined method `value_meals' for #<Chef::DataBagItem:0x00000002d07df0>) on line #6:

  4: <!-- I want to go to <%= @restaurant[ 'nickname' ] %> to get a <%= @restaurant['sandwich'] %>. -->
  5: <!-- But there are also value meals... -->
  6: <% @restaurant.value_meals.each do | meal | %>
  7: <!-- <%= meal.sandwich %>, <%= meal.side %>, and <%= meal.drink %> -->
  8: <% end -%>

先谢谢了!!!

并感谢 CodeRanger !!!

添加以下内容,将其固定在这里,因为我显然还没有格式化评论的诀窍。

<!-- But there are also value meals... -->
<% @restaurant['value_meals'].each do | meal | %>
<!-- <%= meal[ 'sandwich' ] %>, <%= meal[ 'side' ] %>, and <%= meal[ 'drink' ] %> -->
<% end -%>
4

1 回答 1

1

在 Ruby 中访问哈希的方式是通过[]语法,所以@restaurant['value_meals'].eachmeal['side'].

于 2017-08-28T19:08:45.397 回答