2016-02-26 49 views
0

我有一個options_from_collection_for_select看起來像這樣一個select_tagoptions_from_collection_for_select犯規接受哈希作爲參數

<%= select_tag "dash_select", options_from_collection_for_select(session[:user_hotel_list], "id", "name") %> 

我的變量會話[:user_hotel_list]是哈希值的集合看起來是這樣的:

[{"id"=>31, "name"=>"Plaze", "contact_mail"=>"[email protected]", "contact_phone"=>"+33666027414", "address"=>"JDJDJ", "postcode"=>"92200", "city"=>"JDJDJ", "nb_room"=>nil, "created_at"=>"2016-02-26T12:12:39.214Z", "updated_at"=>"2016-02-26T12:12:39.214Z", "auditor_id"=>nil, "account_id"=>48}, {"id"=>30, "name"=>"dndjd", "contact_mail"=>"[email protected]", "contact_phone"=>"+33666027414", "address"=>"k", "postcode"=>"92200", "city"=>"kk", "nb_room"=>nil, "created_at"=>"2016-02-25T22:27:47.035Z", "updated_at"=>"2016-02-25T22:27:47.035Z", "auditor_id"=>nil, "account_id"=>48}] 

不幸的是我得到undefined method名」爲#`

如何將我的對象轉換爲structu那是被接受的軌道options_from_collection_for_select

回答

0

您可以使用options_for_select#collect使這更容易一點。

<%= select_tag "dash_select", options_for_select(session[:user_hotel_list].collect{|h| [h['name'], h['id']]}) %> 

這應該讓你找到你想要的東西,並希望爲你節省一些時間!

答案取自How to populate a select_tag with an array of hashes?

+0

是的我知道這個方法可行,但我也希望在頁面刷新後保持選擇最後一個選擇的項目,並且我使用options_from_collection_for_select方法的最後一個參數 –

+0

來完成。您可以使用options_for_select執行相同的操作:第二個採取的參數是選定的項目:http://apidock.com/rails/v3.2.1/ActionView/Helpers/FormOptionsHelper/options_for_select。 'options_for_select(container,selected = nil)public' – DerProgrammer

+1

好吧,它也適用於options_for_select! –