2017-09-17 43 views
0

我正在爲一家餐廳構建一個應用程序,並且我有一個表單,其中我爲訂單添加了餐點,並且價格字段根據您選擇的菜餚和其中的多少獲取了動態更新。返回表單中的數組時返回一個NoMethodError

要做到這一點我建了一個嵌套的表格(我認爲這並不怎樣都無所謂),它看起來如下:

.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的數組中提取碟的名稱。謝謝!

回答

1

你能澄清你想達到什麼嗎?

這裏是你如何使用collection_select

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

詳細內容見 http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

使用下面的方法文檔

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' 
+0

嘿krishnar,感謝您的回覆。你的例子是collection_select的基本用法。然而,就我而言,我希望在每個選擇選項的HTML標記中包含'data-description'。因此,我正在使用'@ dishes.collect'。 它返回一個名稱和價格的數組。我的問題是我不知道用什麼方法來提取這道菜的名字。正如我所說,這對我來說至關重要,因爲我使用'data-description'來動態地將值傳遞給我的'價格字段' –

+0

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

+0

我將它改爲 = f.select:name,options_for_select(@ dishes.collect {| dish | [dish.name,dish.price,{'data-description'=> dish.price}]}),:class =>'用餐選擇' 我不知道爲什麼,但它正在工作。謝謝! –