Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Array to a select_tag

I currently have this as a search:

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

I have the following list in my user model:

  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"]

I am wondering how do I all the county_options list in to the drop down menu?

like image 371
user1222136 Avatar asked Apr 07 '12 16:04

user1222136


1 Answers

Check out the API documentation for select_tag.

It says:

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

Where option_tags is a string containing the option tags for the select box. You can use other helper methods that turn containers into a string of option tags.

First example:

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

This generates select tags from specific model data.

For your example you should use 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 %>
like image 109
shime Avatar answered Oct 16 '22 09:10

shime