2011-06-15 90 views
1

有人可以請幫助選擇幫手,因爲我是Ruby on rails的新手。Ruby on Rails - 選擇幫助器

我有一個JSON對象作爲跟隨,

@response = {"status" => "200", "fruit" => [ { 
    "id" => 1, 
    "name" => "Apple" 
    }, { 
    "id" => 2, 
    "name" => "Mango" 
    } ] 
} 

對於這幫助我返回值「回報@應答[‘rateCard’]」 現在我從這個幫手要產生這樣的代碼視圖文件,它會選擇框狀

<select name='fruit'> 
<option value="1">apple</option> 
<option value="2" selected>mango</option> 
</select> 

請幫助

其實我已經一個幫手「Fruits_helper.rb」,這是返回

def selFruit 
    @resp = Fruit.getFruit # this will return @response object as mentioned above 

    return @resp['fruit'] 
end 

=========================================== ======================================= 因此,在我的fruit.html.erb文件中,我時遇到小塊代碼如下

<%= form_for(:AdminLogin) do |f| %> 
<div> 

<%= select_tag "fruit", options_for_select(selFruit.each{|fruit,key| [fruit[key]=>'name',fruit[key]=>'id']}) %> 

<div> 
<% end %> 

=================================== ========================================= 上面的代碼給了我o/p as

<select name="fruit" id="fruit"> 
<option value="id1nameApple">id1nameApple</option> 
<option value="id2nameMango">id2nameMango</option> 
</select> 

我想要結果如蘋果

+0

你是怎麼嘗試? – tokland 2011-06-15 19:13:15

+0

form_for - > form.select,而不是select_tag。 selFruit.each - > selFruit.map – tokland 2011-06-16 08:20:25

回答

5

我的問題已經僅僅通過下面的代碼解決了,希望這將有助於其他RoR的新生太

<%= select_tag "fruit", options_for_select(selFruit.map{|fruit,key| [fruit['name'], fruit['id']]}) %> 
+0

與'form_for'表單構建'form.select'是標準方式。 – tokland 2012-04-17 21:07:38

4

如果你使用(你應該)一form_for建設者:

form.select(:fruit, @response["fruit"].map { |f| [f["name"], f["id"]] }) 
+0

上面的代碼拋出錯誤,因爲「錯誤的參數數量(2爲0)」 – 2011-06-16 04:32:29