【发布时间】: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