13

私は現在これを検索として持っています:

 <%= form_tag users_path, :controller => 'users', :action => 'townsearch', :method => 'get' do %>
    <%= select_tag :county, params[:county] %>
    <%= submit_tag 'search'%>
 <% end %>

私のユーザーモデルには次のリストがあります。

  COUNTY_OPTIONS = [ "Avon", "Bedfordshire", "Berkshire", "Borders", "Buckinghamshire", "Cambridgeshire","Central",
                 "Cheshire", "Cleveland", "Clwyd", "Cornwall", "County Antrim", "County Armagh", "County Down",
                 "County Fermanagh", "County Londonderry", "County Tyrone", "Cumbria", "Derbyshire", "Devon",
                 "Dorset", "Dumfries and Galloway", "Durham", "Dyfed", "East Sussex", "Essex", "Fife", "Gloucestershire", 
                 "Grampian", "Greater Manchester", "Gwent", "Gwynedd County", "Hampshire", "Herefordshire", "Hertfordshire",
                 "Highlands and Islands", "Humberside", "Isle of Wight", "Kent", "Lancashire", "Leicestershire", "Lincolnshire",
                 "Lothian", "Merseyside", "Mid Glamorgan", "Norfolk", "North Yorkshire", "Northamptonshire", "Northumberland",
                 "Nottinghamshire", "Oxfordshire", "Powys", "Rutland", "Shropshire", "Somerset", "South Glamorgan", "South Yorkshire",
                 "Staffordshire", "Strathclyde", "Suffolk", "Surrey", "Tayside", "Tyne and Wear", "Warwickshire", "West Glamorgan",
                 "West Midlands", "West Sussex", "West Yorkshire", "Wiltshire", "Worcestershire"]

すべてのcounty_optionsリストをドロップダウンメニューに表示するにはどうすればよいですか?

4

2 に答える 2

26

のAPIドキュメントを確認してくださいselect_tag

それは言う:

select_tag(name, option_tags = nil, options = {}) 

option_tags選択ボックスのオプションタグを含む文字列はどこにありますか。コンテナをオプションタグの文字列に変換する他のヘルパーメソッドを使用できます。

最初の例:

select_tag "people", options_from_collection_for_select(@people, "id", "name")
# <select id="people" name="people"><option value="1">David</option></select>

これにより、特定のモデルデータから選択タグが生成されます。

あなたの例では、を使用する必要がありますoptions_for_select

<%= form_tag users_path, :controller => 'users', :action => 'townsearch', :method => 'get' do %>
    <%= select_tag :county, options_for_select(User::COUNTY_OPTIONS) %>
    <%= submit_tag 'search'%>
 <% end %>
于 2012-04-07T17:04:38.817 に答える
2

collection_selectヘルパーを使いたいと思います。

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#M001593

関連項目:Railsのドロップダウンボックスも参照してください。

于 2012-04-07T17:05:55.267 に答える