【问题标题】:NoMethodError when returning an array in a form在表单中返回数组时出现 NoMethodError
【发布时间】:2017-09-17 13:24:51
【问题描述】:

我正在为一家餐厅构建一个应用程序,我有一个表单,我可以在其中将餐点添加到订单中,并且价格字段会根据您选择的菜肴和数量而动态更新。

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

.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 标记。基于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"})

我认为问题不在于我的控制器,但我会显示它以防万一:

def new
  @dishes = Dish.all
  @order = current_user.orders.build
end

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

总而言之-我的问题是我应该使用什么方法从collection_select 的数组中提取菜肴的名称。谢谢!

【问题讨论】:

    标签: ruby-on-rails arrays ruby forms


    【解决方案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'
    

    【讨论】:

    • 嗨,克里希纳,感谢您的回复。您的示例是 collection_select 的基本用法。但是,就我而言,我想在每个选择选项的 HTML 标记中包含 data-description。因此,我使用@dishes.collect。它返回一个带有名称和价格的数组。我的问题是我不知道应该用什么方法来提取菜名。正如我所说,这对我来说至关重要,因为我使用data-description 将值动态传递给我的“价格字段”
    • = f.select :meal_select, options_for_select(@dishes.collect{ |dish| [dish.name,dish.price,{'data-description' =>dish.price}]}), :class=> '膳食选择'
    • 我把它改成了 = f.select :name, options_for_select(@dishes.collect{ |dish| [dish.name, disc.price,{'data-description' => disc.price} ]}), :class=> 'meal-select' 我不知道为什么,但它起作用了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    相关资源
    最近更新 更多