我有3个级联下拉列表命名;国家,城市和地区。它们之间的关系如下;
#country.rb
class Country < ActiveRecord::Base
has_many :cities
has_many :districts, :through => :cities
end
#city.rb
class City < ActiveRecord::Base
belongs_to :country
has_many :districts
end
#district.rb
class District < ActiveRecord::Base
belongs_to :city
end
我有一个问题,当我在Chrome响应的网络选项卡中选择国家和城市时,似乎是正确的,但列表不会自行更新。这是它的样子;
所以我选择法国 - 尼斯,但最后一次下拉必须显示5,6,7,8而不是1,2,3,4。但是,在响应选项卡上看起来很好;
但无论我选择哪个城市或国家/地区的回复都很好,但它没有显示在下拉列表中。
这是我的controller
;
class WelcomeController < ApplicationController
def index
@countries = Country.all
@cities = City.where("country_id = ?", Country.first.id)
@districts = District.where("city_id = ?", City.first.id)
end
def show
@city = City.find_by("id = ?", params[:trip][:city_id])
@district = District.find_by("id = ?", params[:trip][:district_id])
end
def update_cities
@cities = City.where("country_id = ?", params[:country_id])
respond_to do |format|
format.js
end
end
def update_districts
@districts = District.where("city_id = ?", params[:city_id])
respond_to do |format|
format.js
end
end
end
这是index.html
文件;
<%= form_for :trip, url: {action: "show"}, html: {method: "get"} do |f| %>
<%= f.select :country_id, options_for_select(@countries.collect { |country|
[country.name.titleize, country.id] }, 1), {}, { id: 'countries_select' } %>
<%= f.select :city_id, options_for_select(@cities.collect { |city|
[city.name.titleize, city.id] }, 0), {}, { id: 'cities_select' } %>
<%= f.select :district_id, options_for_select(@districts.collect { |district|
[district.name.titleize, district.id] }, 0), {}, { id: 'district_select' } %>
<%= f.submit "Go!" %>
<% end %>
索引districts/_district.html.erb
<option value="<%= district.id %>"><%= district.name.titleize %></option>
cities/_city.html.erb
<option value="<%= city.id %>"><%= city.name.titleize %></option>
最后,welcome.coffee
$ ->
$(document).on 'change', '#countries_select', (evt) ->
$.ajax 'update_cities',
type: 'GET'
dataType: 'script'
data: {
country_id: $("#countries_select option:selected").val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic country select OK!")
$ ->
$(document).on 'change', '#cities_select', (evt) ->
$.ajax 'update_districts',
type: 'GET'
dataType: 'script'
data: {
city_id: $("#cities_select option:selected").val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic country select OK!")
我不知道我在哪里做错了,因为它似乎有效,但却对视图造成了麻烦。所以它可能是<option>
标签但是找不到它。
非常感谢您的帮助