Skip to content

Instantly share code, notes, and snippets.

@cv711
Last active December 19, 2015 14:08
Show Gist options
  • Save cv711/5966631 to your computer and use it in GitHub Desktop.
Save cv711/5966631 to your computer and use it in GitHub Desktop.
Synchronize country and city selection in a form
<% if !@cities.blank? %>
$('#cityfield').html("");
$('#cityfield').html("<%=j collection_select(:resource,:CITY_ID,Country.find(1).cities,:id,:NAME, {:prompt =>'Select a city'})%>");
<%else%>
$('#cityfield').html("");
$('#cityfield').html("<%=j text_field :CITY_ID, :disabled%>");
<%end%>
def edit
@title = "Edit resource info"
@station = Resource.find(params[:id])
#protect the ui from null values
if !@station.CITY_ID.blank? && @station.CITY_ID>0
@station_country_name = Country.find(City.find(@station.CITY_ID).COUNTRY_ID).NAME
@station_city_name = City.find(@station.CITY_ID)
else
@station_country_name = ""
@station_city_name = ""
end
end
...
def city_partial
if !params[:country_id].blank? && params[:country_id].to_i>0
@cities = Country.find(params[:country_id]).cities
else
@cities = nil
end
end
...
<% f.collection_select(:country,Country.all,:id,:NAME,
:include_blank => (true if @station_country_name.blank?),
:selected => (@station_country_name unless @station_country_name.blank?) )%>
<span class="help-block">Country</span>
...
<% f.collection_select(:CITY_ID, ( ([@station_city_name] unless @station_city_name.blank?) || []),:id, :NAME, :selected => @station_city_name ) %>
<span class="help-block">City</span>
...
<script type="text/javascript">
$("#resource_country").change(function(){
var country_id = $('select#resource_country :selected').val();
if(country_id =="") country_id="0";
$.get('/users/resource/city_partial/'+country_id);
});
</script>
<% end %> //of form
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment