Ruby on Rails - 选择国家和州时加载州和城市
Ruby on Rails - Load State and city when Country and State is selected
我有 countries, states & cities
个数据库及其模型 Country, State & City
。
当前关联:
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
目前我使用此 jQuery 仅显示基于 selected 国家/地区的州,但它仍会加载 select[options] 中的所有州,这会减慢页面加载速度.
- 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()
在我的表单中(我正在使用 Simple_form_for),如何为 [ 添加 collection_select/select =14=] 和 ONLY LOAD, states when a country is selected and当州被select编辑时加载城市?
PS:加载的州和城市需要根据哪个国家和州selected。
是否有任何 gem 适合我正在寻找的东西或 Ajax 解决方案?
(也欢迎其他解决方案)
您可以在 rails 中做到这一点,而无需使用任何 gem。
f.collection_select(:state_id, State.all, :id, :name, {},{:data => { :remote => true,
:url => url_for(:controller => "states",
:action => "display_cities")
}
}
)
在 display_cities 操作中,根据通过的 state_id 筛选城市。使用 display_cities.js.erb 生成新的 html 填充 div 元素。
我有 countries, states & cities
个数据库及其模型 Country, State & City
。
当前关联:
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
目前我使用此 jQuery 仅显示基于 selected 国家/地区的州,但它仍会加载 select[options] 中的所有州,这会减慢页面加载速度.
- 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()
在我的表单中(我正在使用 Simple_form_for),如何为 [ 添加 collection_select/select =14=] 和 ONLY LOAD, states when a country is selected and当州被select编辑时加载城市?
PS:加载的州和城市需要根据哪个国家和州selected。
是否有任何 gem 适合我正在寻找的东西或 Ajax 解决方案? (也欢迎其他解决方案)
您可以在 rails 中做到这一点,而无需使用任何 gem。
f.collection_select(:state_id, State.all, :id, :name, {},{:data => { :remote => true,
:url => url_for(:controller => "states",
:action => "display_cities")
}
}
)
在 display_cities 操作中,根据通过的 state_id 筛选城市。使用 display_cities.js.erb 生成新的 html 填充 div 元素。