Country state city dropdown for ruby on rails admin form

Viewed 14

I need a drop-down in my admin form with with names country, state and city. when the former the selected the rest should be filtered accordingly.

There are few solutions a went through but found it complex to implement. Knowing ruby so far the ways are expected to be simpler. I'm new to ruby...would appreciate a step wise explanation.

1 Answers

you can have something like in your view

# app/views/address.html.haml

= form_for @address, do |f|
  = f.label :country, "Country"
  = f.select :country, @countries
  
  = f.label :state, "State"
  = f.select :state, []

  = f.label :city, "City"
  = f.select :city, []

Write js to auto-populate state and city values

# app/assets/javascripts/address.js

$('#country').on('change', (e) ->
  if $(this).val() != ''
    type: 'GET'
    data:
      country: $(this).value
    url: '/get_country_wise_state'
    success: (data, status) ->
    options = createStateDropDown(data)
    options = ''
    $.each data, (index, state) ->
      options += "<option value = '" + state + "'>" + state + "</option>"
    select_tag = "<select id=state name=state>" + options + "</select>"
    $('#state').replaceWith(select_tag)
)

Now write API to fetch state using country name.

# app/controller/address_controller.rb

def get_country_wise_state
  country_name = params[:country]

  # logic to get array of states.

  render :json => state_array
end

Similarly, you can do this for cities by creating API and js.

I hope this will help you.

Related