Rubioli
Rubioli

Reputation: 680

Ruby on Rails - Load State and city when Country and State is selected

I have countries, states & cities Databases with their models Country, State & City.

Current association:

class Country < ActiveRecord::Base
  has_many :states
end

class State < ActiveRecord::Base
  belongs_to :country
  has_many :cities
end

class City < ActiveRecord::Base
  belongs_to :state
end

Currently Im using this jQuery to only show states based on selected country, but it still loads all the states in the select[options] which slows down page load.

- jQuery ->
  states = $('#q_state_id_eq').html()
  update_states = ->
    country = $('#q_country_id_eq :selected').text()
    options = $(states).filter("optgroup[label=#{country}]").html()

    if options
      $('#q_state_id_eq').html(options)
      # Add in a blank option at the top
      $('#q_state_id_eq').prepend("<option value=''></option>")
      # Ensure that the blank option is selected
      $('#q_state_id_eq option:first').attr("selected", "selected");
    else
      $('#q_state_id_eq').empty()

  $('#q_country_id_eq').change ->
    update_states()

  update_states()

In my form (I am using Simple_form_for), how can I add collection_select/select for countries, states & cities and ONLY LOAD, states when a country is selected and load cities when a state is selected?

PS: Loaded states and cities needs to be based on which country and state is selected.

Is there any gem for what I am looking for or a Ajax solution? (other solutions are also appreciated)

Upvotes: 0

Views: 2404

Answers (1)

Bijendra
Bijendra

Reputation: 10035

You can do that in rails without using any gem.

f.collection_select(:state_id, State.all, :id, :name, {},{:data => {  :remote => true,
                :url => url_for(:controller => "states", 
                                :action => "display_cities")
            }
    }
)

In display_cities action, filter cities based on the state_id passed. Use display_cities.js.erb to populate the div element with new html generated.

Upvotes: 2

Related Questions