返回表单中的数组时出现NoMethodError

时间:2017-09-17 13:24:52

标签: ruby-on-rails arrays ruby forms

我正在为一家餐馆建立一个应用程序,我有一个表单,我可以在其中添加一份订单,价格字段会根据您选择的菜肴和菜单数量进行动态更新。

为此,我构建了一个嵌套表单(我认为无论如何都不重要),如下所示:

.nested-fields
  = f.collection_select(0, @dishes.collect{ |dish| [dish.name, :data => {:description => dish.price}]}, :name, :name, {include_blank: true}, {class: "meal-select"})
  = f.select :quantity, options_for_select((1..10))
  = f.text_field(:price, disabled: true)
  = link_to_remove_association "X", f

让我烦恼的是collection_select。如您所见,我将返回一个名称为data-description的数组,该数组将转到HTML标记。根据{{​​1}},我的价格字段会更新。

但是,我不知道应该选择哪种方法来提取菜肴的名称。正如你所看到的,我尝试data-description,因为这个菜的名字总是在数组中的第一个。我也尝试了0:first,但这些都没有!我得到的错误是:

:name

或当我使用"NoMethodError in Orders#new undefined method '0' for #Meal:0x007fe4eb8e26c8"

:name

当然,它指向:

undefined method `name' for ["Zupa z Krewetkami", {:data=>
{:description=>17.0}}]:Array

我不认为问题出在我的控制器上,但是,为了以防万一,我会展示它:

= f.collection_select(0, @dishes.collect{ |dish| [dish.name, :data => {:description => dish.price}]}, :name, :name, {include_blank: true}, {class: "meal-select"})

我尝试寻找答案here,但正如您所看到的那样,问题尚未解决,而且与我的问题略有不同。

总结一下 - 我的问题是我应该使用什么方法从def new @dishes = Dish.all @order = current_user.orders.build end 中的数组中提取菜肴的名称。谢谢!

1 个答案:

答案 0 :(得分:1)

以下是如何使用collection_select

...
= f.collection_select :meal_select, @dishes, :name, :price, {include_blank: true}, {class: "meal-select"}
...

有关详情see the docs

使用以下方法

options_for_select( [['First', 1, {:'data-price' => 20}],
                     ['Second', 2, {:'data-price' => 30}]] )


= f.select :meal_select, options_for_select(@dishes.collect{ |dish| [dish.name, dish.price,{'data-description' => dish.price}]}), :class => 'meal-select'