我在制造动态的衰退时遇到困难:
当你选择一个国家时,它使部分城市属于一个国家。
我有这样的模式:国家拥有——城市,城市属于国家。
随着火力的推移,我在选择联系记录而不是国家记录时,将控制者的行动更新——城市——当选。
I followed the example from Peter Mac
我的守则是:
申请:js
jQuery(function($) {
// when the #region_id field changes
$("#contact_country_id").live( change , function() {
// make a POST call and replace the content
var country = $( select#contact_country_id :selected ).val();
if(country == "") country="0";
jQuery.get( /contacts/update_city_select/ + country, function(data){
$("#cities").html(data);
})
return false;
});
})
联系人:控制员。
def new
@contact = Contact.new
@industries = Industry.all
@countries = Country.all
@cities = City.where(["country_id = ?", 1]).all
respond_to do |format|
format.html # new.html.erb
format.json { render json: @contact }
end
end
.
.
.
def update_city_select
@cities = City.where(:country_id => params[:id]).order(:name) unless params[:id].blank?
render :partial => "cities", :locals => { :cities => @cities }
end
联系/_form.html.erb
<%= form_for(@contact) do |f| %>
...
<div class="field">
<%= f.label :country %>
<%= f.collection_select :country_id, @countries, :id, :name, :prompt => "-- Select a country --" %>
</div>
<div id="cities" class="field">
<%= render cities %>
</div>
...
<% end %>
联系/单位:html。
<%= fields_for @contact do |f| %>
<%= f.label :city %>
<% unless cities.blank? %>
<%= f.collection_select :city_id, cities, :id, :name, :prompt => "-- Select a city --" %>
<% else %>
<%= f.select "city_id","city_id", :prompt => "-- Select a city --" %>
<% end %>
<% end %>
路线。
resources :cities
resources :countries
resources :contacts
get /contacts/update_city_select/:id => contacts#update_city_select
请你帮助解决阿贾克斯问题!
Aurelien