Search code examples
ruby-on-railscarmen

carmen-rails subregion select (combine Canadian provinces and US states)


I have a dropdown with US states and territories. I would like to add Canadian provinces so that the entire list is states/provinces in alphabetical order.

Currently I have this code which lists all US states and territories:

= extra_fields.input :province, label: "Franchisee Billing State/Province", input_html: { class: "form-control" } do
    = extra_fields.subregion_select(:province, "US", {prompt: 'Please select a state'}, required: 'region required')

I tried converting the second parameter of subregion_select to ["US, "CA"] but that breaks things.


Solution

  • As per my understanding you are looking for union of Canadian provinces and US states for a select field without country_select functionality. If am i right, you can get by this way

    countries = Carmen::Country.all.select{|c| %w{US CA}.include?(c.code)} # get the countries
    # get the subregions of US and CA
    subregions = countries.collect {|x| x.subregions }.flatten 
    

    In rails application

    Create helper method

    def subregions_of_us_and_canada
      countries = Carmen::Country.all.select{|c| %w{US CA}.include?(c.code)}
      # get subregions and sort in alphabetical order  
      countries.collect {|x| x.subregions }.flatten.sort_by(&:name)
    end
    

    Call the above method in form

    = extra_fields.input :province, as: :select, collection: subregions_of_us_and_canada, label_method: :name, value_method: :code, label: "Franchisee Billing State/Province", input_html: { class: "form-control" }, prompt: 'Please select a state'
    

    I hope this would be helpfull