Plugin: state_select, generate drop down selection box for states

Published on Author Akhil Bansal47 Comments

I have wrote my first plugin(state_select). This plugin allows to create drop down list for states, same as country_select method in rails. I know this is not a big deal…

UPDATE: Curently it can generate state list for INDIA, US, UK, CANADA, AUSTRALIA, SPAIN, FRANCE, UGANDA, GERMAN and NETHERLANDS.

Usage:

 
state_select(object, method, country='US', options = {}, html_options = {}) 

Return select and option tags for the given object and method, using state_options_for_select to generate the list of option tags.

 
 state_options_for_select(selected = nil, country = 'US') 

Returns a string of option tags for states in a country. Supply a state name as selected to have it marked as the selected option tag.

NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.

github URL: http://github.com/bansalakhil/state_select

Install plugin by

script/plugin install  git://github.com/bansalakhil/state_select.git

47 Responses to Plugin: state_select, generate drop down selection box for states

  1. Here is a patch to add Australian states:

    Index: lib/state_select.rb
    ===================================================================
    — lib/state_select.rb (revision 1)
    +++ lib/state_select.rb (working copy)
    @@ -23,6 +23,7 @@
    US_STATES=[“Alaska”, “Alabama”, “Arkansas”, “Arizona”, “California”, “Colorado”, “Connecticut”, “Washington D.C.”, “Delaware”, “Florida”, “Georgia”, “Hawaii”, “Iowa”, “Idaho”, “Illinois”, “Indiana”, “Kansas”, “Kentucky”, “Louisiana”, “Massachusetts”, “Maryland”, “Maine”, “Michigan”, “Minnesota”, “Missourri”, “Mississippi”, “Montana”, “North Carolina”, “North Dakota”, “Nebraska”, “New Hampshire”, “New Jersey”, “New Mexico”, “Nevada”, “New York”, “Ohio”, “Oklahoma”, “Oregon”, “Pennsylvania”, “Puerto Rico”, “Rhode Island”, “South Carolina”, “South Dakota”, “Tennessee”, “Texas”, “Utah”, “Virginia”, “Vermont”, “Washington”, “Wisconsin”, “West Virginia”, “Wyoming”] unless const_defined?(“US_STATES”)
    INDIA_STATES=[“Andhra Pradesh”, “Arunachal Pradesh”, “Assam”, “Bihar”, “Chhattisgarh”, “New Delhi”, “Goa”, “Gujarat”, “Haryana”, “Himachal Pradesh”, “Jammu and Kashmir”, “Jharkhand”, “Karnataka”, “Kerala”, “Madhya Pradesh”, “Maharashtra”, “Manipur”, “Meghalaya”, “Mizoram”, “Nagaland”, “Orissa””Punjab”, “Rajasthan”, “Sikkim”, “Tamil Nadu”, “Tripura”, “Uttaranchal”, “Uttar Pradesh”, “West Bengal”] unless const_defined?(“INDIA_STATES”)
    CANADA_STATES=[“Alberta”, “British Columbia”, “District of Columbia”, “Manitoba”, “New Brunswick”, “Newfoundland and Labrador”, “Northwest Territories”, “Nova Scotia”, “Nunavut”, “Prince Edward Island”, “Saskatchewan”, “Ontario”, “Quebec”] unless const_defined?(“CANADA_STATES”)
    + AUSTRALIA_STATES=[“Australian Capital Territory”, “New South Wales”, “Northern Territory”, “Queensland”, “South Australia”, “Tasmania”, “Victoria”, “Western Australia”] unless const_defined?(“AUSTRALIA_STATES”)
    end

    class ActionView::Helpers::InstanceTag
    Index: README
    ===================================================================
    — README (revision 1)
    +++ README (working copy)
    @@ -6,7 +6,7 @@
    Usage:
    state_select(object, method, country=’INDIA’, options = {}, html_options = {})

    – Currently it supports only India, US and Canada
    + Currently it supports only India, US, Canada and Australia

    If you want to add other country plese send me the list of states and I will add them.

  2. ES_STATES=[ “Alava”, “Albacete”, “Alicante”, “Almeria”, “Asturias”, “Avila”, “Badajoz”, “Barcelona”, “Burgos”, “Caceres”, “Cadiz”, “Cantrabria”, “Castellón”, “Ceuta”, “Ciudad Real”, “Cordoba”, “Coruña, A”, “Cuenca”, “Girona”, “Granada”, “Guadalajara”, “Guipuzcoa”, “Huelva”, “Huesca”, “Islas Baleares”, “Jaen”,”León”, “Lleida”, “Lugo”, “Madrid”, “Malaga”, “Melilla”, “Murcia”, “Navarra”, “Ourense”, “Palencia”, “Palmas, Las”, “Pontevedra”, “Rioja, La”, “Salamanda”, “Santa Cruz de Tenerife”, “Segovia”, “Sevila”, “Soria”, “Tarragona”, “Teruel”, “Toledo”, “Valencia”, “Valladolid”, “Vizcaya”, “Zamora”, “Zaragoza”] unless const_defined?(“ES_STATES”)

  3. Is there something available, or could you possibly write something to provide easy validation that verfies an actual entry was submitted? I would rather not write out all 50 states, and I think it’d be an improvment to the plugin.

    Thanks,
    Ryan

  4. UGANDA_STATES=[“Abim”, “Adjumani”, “Amolatar”, “Amuria”, “Apac”, “Arua”, “Budaka”, “Bugiri”, “Bukwa”, “Bulisa”, “Bundibugyo”, “Bushenyi”, “Busia”, “Busiki”, “Butaleja”, “Dokolo”, “Gulu”, “Hoima”, “Ibanda”, “Iganga”, “Jinja”, “Kaabong”, “Kabale”, “Kabarole”, “Kaberamaido”, “Kabingo”, “Kalangala”, “Kaliro”, “Kampala”, “Kamuli”, “Kamwenge”, “Kanungu”, “Kapchorwa”, “Kasese”, “Katakwi”, “Kayunga”, “Kibale”, “Kiboga”, “Kilak”, “Kiruhura”, “Kisoro”, “Kitgum”, “Koboko”, “Kotido”, “Kumi”, “Kyenjojo”, “Lira”, “Luwero”, “Manafwa”, “Maracha”, “Masaka”, “Masindi”, “Mayuge”, “Mbale”, “Mbarara”, “Mityana”, “Moroto”, “Moyo”, “Mpigi”, “Mubende”, “Mukono”, “Nakapiripirit”, “Nakaseke”, “Nakasongola”, “Nebbi”, “Ntungamo”, “Oyam”, “Pader”, “Pallisa”, “Rakai”, “Rukungiri”, “Sembabule”, “Sironko”, “Soroti”, “Tororo”, “Wakiso”, “Yumbe”] unless const_defined?(“UGANDA_STATES”)

  5. FRANCE_STATES=[“Alsace”,”Aquitaine”,”Auvergne”,”Bourgogne”,”Bretagne”,”Centre”,”Champagne-Ardenne”,”Corse”,”Franche-Comté”,”ÃŽle-de-France”,”Languedoc-Roussillon”,”Limousin”,”Lorraine”,”Midi-Pyrénées”,”Nord-Pas-de-Calais”,”Basse-Normandie”,”Haute-Normandie”,”Pays de la Loire”,”Picardie”,”Poitou-Charentes”,”Provence-Alpes-Côte d’Azur”,”Rhône-Alpes”] unless const_defined?(“FRENCH_STATES”)

  6. To make this AJAX like, I had to do a little extra work. For instance, the country Germany requires the form helper to say GERMAN, United States to say US, etc. It would be nice if the constant was a capital version of the country and if there was no country, it would show a text field for entry.

    0.5,
    :update=>"state_select",
    :url=> {:action=>'state_select', :only_path=>false},
    :with=>"'country=' + encodeURIComponent(value)" %>

    would link to a partial


    instead of…

    "text" %>

  7. BRAZIL_STATES=[“Acre”
    “Alagoas”
    “Amapá”
    “Amazonas”
    “Bahia”
    “Ceará”
    “Distrito Federal”
    “Goiás”
    “Espírito Santo”
    “Maranhão”
    “Mato Grosso”
    “Mato Grosso do Sul”
    “Minas Gerais”
    “Pará”
    “Paraiba”
    “Paraná”
    “Pernambuco”
    “Piauí”
    “Rio de Janeiro”
    “Rio Grande do Norte”
    “Rio Grande do Sul”
    “Rondônia”
    “Rorâima”
    “São Paulo”
    “Santa Catarina”
    “Sergipe”
    “Tocantins”] unless const_defined?(”BRAZIL_STATES”)

  8. sorry, last post wasn’t nice…
    i forgot the commas… hehe
    here is the good one:

    BRAZIL_STATES=[“Acre”, “Alagoas”, “Amapá”, “Amazonas”, “Bahia”,”Ceará”, “Distrito Federal”, “Goiás”, “Espírito Santo”, “Maranhão”, “Mato Grosso”, “Mato Grosso do Sul”, “Minas Gerais”, “Pará”, “Paraiba”, “Paraná”, “Pernambuco”, “Piauí”, “Rio de Janeiro”, “Rio Grande do Norte”, “Rio Grande do Sul”, “Rondônia”, “Rorâima”, “São Paulo”, “Santa Catarina”, “Sergipe”, “Tocantins”] unless const_defined?(“BRAZIL_STATES”)

  9. Thanks Kaith,it works great but I faced
    one problem with it ,options={} and html_options ={} is does not work.How can I put class or id for it.

  10. Here is US states with 2 char codes:
    US_WITH_CODE_STATES = [[‘Alabama’, ‘AL’], [‘Alaska’, ‘AK’], [‘Arizona’, ‘AZ’], [‘Arkansas’, ‘AR’], [‘California’, ‘CA’], [‘Colorado’, ‘CO’], [‘Connecticut’, ‘CT’], [‘Delaware’, ‘DE’], [‘District Of Columbia’, ‘DC’], [‘Florida’, ‘FL’],[‘Georgia’, ‘GA’],[‘Hawaii’, ‘HI’], [‘Idaho’, ‘ID’], [‘Illinois’, ‘IL’], [‘Indiana’, ‘IN’], [‘Iowa’, ‘IA’], [‘Kansas’, ‘KS’], [‘Kentucky’, ‘KY’], [‘Louisiana’, ‘LA’], [‘Maine’, ‘ME’], [‘Maryland’, ‘MD’], [‘Massachusetts’, ‘MA’], [‘Michigan’, ‘MI’], [‘Minnesota’, ‘MN’], [‘Mississippi’, ‘MS’], [‘Missouri’, ‘MO’], [‘Montana’, ‘MT’], [‘Nebraska’, ‘NE’], [‘Nevada’, ‘NV’], [‘New Hampshire’, ‘NH’], [‘New Jersey’, ‘NJ’], [‘New Mexico’, ‘NM’], [‘New York’, ‘NY’], [‘North Carolina’, ‘NC’], [‘North Dakota’, ‘ND’], [‘Ohio’, ‘OH’], [‘Oklahoma’, ‘OK’], [‘Oregon’, ‘OR’], [‘Pennsylvania’, ‘PA’], [‘Rhode Island’, ‘RI’], [‘South Carolina’, ‘SC’], [‘South Dakota’, ‘SD’], [‘Tennessee’, ‘TN’], [‘Texas’, ‘TX’], [‘Utah’, ‘UT’], [‘Vermont’, ‘VT’], [‘Virginia’, ‘VA’], [‘Washington’, ‘WA’], [‘West Virginia’, ‘WV’], [‘Wisconsin’, ‘WI’], [‘Wyoming’, ‘WY’]] unless const_defined?(“US_WITH_CODE_STATES”)

  11. This is a great timesaver. But is there a way for it to take the value from the object/method passed to it? i.e. if i am updating a record, i would like it to start at the existing value, rather than the first item in the list. (this is how country_select works.)

  12. Hey – just wanted to second what Timur said. Having the state postal codes is a big help. I used that as he posted, except I named it “US_POSTAL_STATES”. That seemed a bit more semantic to me.

    Thanks – it’s a great help!

  13. I put together a list of just the postal codes – no state names – for the US. List was compiled from the USPS official postal codes list of the US and major outlying areas.

    US_POSTAL_CODES_STATES = [‘AK’,’AL’,’AR’,’AS’,’AZ’,’CA’,’CO’,’CT’,’DC’,’DE’,’FL’,’FM’,’GA’,’GU’,’HI’,’IA’,’ID’,’IL’,’IN’,’KS’,’KY’,’LA’,’MA’,’MD’,’ME’,’MH’,’MI’,’MN’,’MO’,’MP’,’MS’,’MT’,’NC’,’ND’,’NE’,’NH’,’NJ’,’NM’,’NV’,’NY’,’OH’,’OK’,’OR’,’PA’,’PR’,’PW’,’RI’,’SC’,’SD’,’TN’,’TX’,’UT’,’VA’,’VI’,’VT’,’WA’,’WI’,’WV’,’WY’]
    unless const_defined?(“US_POSTAL_CODES_STATES”)

  14. In response to Matt I played with this for about an hour and a half before I gained any functionality. Here’s my code (my object is a TV Station, “station” and my method is “state”)

    State:

    I inserted a blank option field so if no state is given it doesn’t get set to AK or Alabama by default. The state will get set if it exists (for an edit type function) but if it does not exist it will be blank.

    PS I had to restart the web server after modifying the state_select.rb file in the plugin.

  15. Hi, I am getting this error:

    ActionView::TemplateError (uninitialized constant ActionView::Base::CompiledTemplates::US) on line

    But this works:

  16. POLAND_STATES=[“DolnoÅ›lÄ…skie”, “Kujawsko-Pomorskie”, “Lubelskie”, “Lubuskie”, “Łódzkie”, “MaÅ‚opolskie”, “Mazowieckie”, “Opolskie”, “Podkarpackie”, “Podlaskie”, “Pomorskie”, “ÅšlÄ…skie”, “ÅšwiÄ™tokrzyskie”, “WarmiÅ„sko-Mazurskie”, “Wielkopolskie”, “Zachodniopomorskie”] unless const_defined?(“POLAND_STATES”)

  17. Counties for Republic of Ireland: IE_STATES=[“Carlow”,”Cavan”,”Cork”,”Clare”,”Donegal”,”Dublin”,”Galway”,”Kerry”,”Kildare”,”Kilkenny”,”Laois”,”Leitrim”,”Limerick”,”Longford”,”Louth”,”Mayo”,”Meath”,”Monaghan”,”Offaly”,”Roscommon”,”Sligo”,”Tipperary”,”Waterford”,”Westmeath”,”Wexford”,”Wicklow”] unless const_defined?(“IE_STATES”)
    Counties for Northern Ireland:
    NI_STATES=[“Antrim”,”Armagh”,”Derry”,”Down”, “Fermanagh”,”Tyrone”] unless const_defined?(“NI_STATES”)

  18. Might I suggest changing your current US_STATES to US_UNABBREV_STATES and adding the following:

    US_STATES=[
    [ “Alabama”, “AL” ],
    [ “Alaska”, “AK” ],
    [ “Arizona”, “AZ” ],
    [ “Arkansas”, “AR” ],
    [ “California”, “CA” ],
    [ “Colorado”, “CO” ],
    [ “Connecticut”, “CT” ],
    [ “Delaware”, “DE” ],
    [ “District Of Columbia”, “DC” ],
    [ “Florida”, “FL” ],
    [ “Georgia”, “GA” ],
    [ “Hawaii”, “HI” ],
    [ “Idaho”, “ID” ],
    [ “Illinois”, “IL” ],
    [ “Indiana”, “IN” ],
    [ “Iowa”, “IA” ],
    [ “Kansas”, “KS” ],
    [ “Kentucky”, “KY” ],
    [ “Louisiana”, “LA” ],
    [ “Maine”, “ME” ],
    [ “Maryland”, “MD” ],
    [ “Massachusetts”, “MA” ],
    [ “Michigan”, “MI” ],
    [ “Minnesota”, “MN” ],
    [ “Mississippi”, “MS” ],
    [ “Missouri”, “MO” ],
    [ “Montana”, “MT” ],
    [ “Nebraska”, “NE” ],
    [ “Nevada”, “NV” ],
    [ “New Hampshire”, “NH” ],
    [ “New Jersey”, “NJ” ],
    [ “New Mexico”, “NM” ],
    [ “New York”, “NY” ],
    [ “North Carolina”, “NC” ],
    [ “North Dakota”, “ND” ],
    [ “Ohio”, “OH” ],
    [ “Oklahoma”, “OK” ],
    [ “Oregon”, “OR” ],
    [ “Pennsylvania”, “PA” ],
    [ “Rhode Island”, “RI” ],
    [ “South Carolina”, “SC” ],
    [ “South Dakota”, “SD” ],
    [ “Tennessee”, “TN” ],
    [ “Texas”, “TX” ],
    [ “Utah”, “UT” ],
    [ “Vermont”, “VT” ],
    [ “Virginia”, “VA” ],
    [ “Washington”, “WA” ],
    [ “West Virginia”, “WV” ],
    [ “Wisconsin”, “WI” ],
    [ “Wyoming”, “WY” ] ] unless const_defined?(“US_STATES”)

  19. Hey guys,
    I’m trying to have a selected state and a none option to the state_select. I wasn’t successful getting that to work. I tried everything but no luck. could you give me an example please.

    Thanks

  20. […] Web On Rails – » Plugin: state_select, generate drop down selection box for states | Its all about RubyOnRails(ROR) Plugin: state_select, generate drop down selection box for states (tags: rails plugin plugins state_select rubyonrails) […]

  21. MEXICO_STATES = [“Aguascalientes”, “Baja California”, “Baja California Sur”, “Campeche”, “Chiapas”, “Chihuahua”, “Coahuila”, “Colima”, “Distrito Federal”, “Durango”, “Guanajuato”, “Guerrero”, “Hidalgo”, “Jalisco”, “Michoacán”, “Morelos”, “México”, “Nayarit”, “Nuevo León”, “Oaxaca”, “Puebla”, “Querétaro”, “Quintana Roo”, “San Luis Potosí”, “Sinaloa”, “Sonora”, “Tabasco”, “Tamaulipas”, “Tlaxcala”, “Veracruz”, “Yucatán”, “Zacatecas”]

  22. ES_STATES has a typo in Salamanca, correct is:

    ES_STATES=[ “Alava”, “Albacete”, “Alicante”, “Almeria”, “Asturias”, “Avila”, “Badajoz”, “Barcelona”, “Burgos”, “Caceres”, “Cadiz”, “Cantrabria”, “Castellón”, “Ceuta”, “Ciudad Real”, “Cordoba”, “Coruña, A”, “Cuenca”, “Girona”, “Granada”, “Guadalajara”, “Guipuzcoa”, “Huelva”, “Huesca”, “Islas Baleares”, “Jaen”,”León”, “Lleida”, “Lugo”, “Madrid”, “Malaga”, “Melilla”, “Murcia”, “Navarra”, “Ourense”, “Palencia”, “Palmas, Las”, “Pontevedra”, “Rioja, La”, “Salamanca”, “Santa Cruz de Tenerife”, “Segovia”, “Sevila”, “Soria”, “Tarragona”, “Teruel”, “Toledo”, “Valencia”, “Valladolid”, “Vizcaya”, “Zamora”, “Zaragoza”] unless const_defined?(”ES_STATES”)

  23. Hello Akhil,

    I ended up using your state_select plugin. Works well. I recently upgraded my gems version to 2.2.2 from 2.1.2. And state_select fails to work there. I downgraded it back to 2.1.2 and it works.

    I will be looking for the problem and post the solution, if I find one. But just a heads up, if you are aware about it and can post a quick fix.

    Thanks.

  24. Hey Akhil,

    Thanks. I was getting Wrong number of arguments error. Now, I understand why that tag helper did not worked in 2.2.2

  25. Hi guys. I’m relatively new to Rails, but am loving it so far. I’m having trouble getting this thing to work. I have it set up and the drop down menu is in place, but I keep getting the message: “State can’t be blank.”

    I’m using it in a form like so:

    In addition to the validates_presence_of list, I also added this to the module file where it is used:
    def state
    state = read_attribute(:state)
    end

    And this in the controller file:
    @user.state = params[:user][:state]

    I’m sure I’m just missing something out of ignorance, but any help would be appreciated. Thanks!

  26. Any thoughts on my last question?

    It seems that I might not have the users module and controller set up properly. Like I mentioned, I’m relatively new, so any help would be appreciated.

    Thanks.

  27. Canadian provinces with abbreviations:

    CANADA_PROVINCES_FOR_SELECT = [[“Alberta”, ‘AB’], [“British Columbia”, ‘BC’], [“Manitoba”, ‘MB’], [“New Brunswick”, ‘NB’], [“Newfoundland and Labrador”, ‘NL’], [“Northwest Territories”, ‘NT’], [“Nova Scotia”, ‘NS’], [“Nunavut”, ‘NU’], [“Ontario”, ‘ON’], [“Prince Edward Island”, ‘PE’], [“Quebec”, ‘QC’], [“Saskatchewan”, ‘SK’], [‘Yukon’, ‘YT’]]

    • i still am not getting how to implement this in my app. i have downloaded the plugin and installed as well.but am not getting how to work it out .please can anyone help me out in this.

      Thanks

  28. Thanks. I was getting Wrong number of arguments error. Now, I understand why that tag helper did not worked..Please tell me in details how to work it out .

Leave a Reply

Your email address will not be published. Required fields are marked *