我有countries, states & cities
数据库和他们的型号Country, State & City
。Ruby on Rails - 选择国家和州时,加载州和城市
流通协会:
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,只显示状态基础上选定的国家,但它仍然加载在选择[选项]所有的州这将减慢页面加载。
- 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),当国家选择和负载城市为countries, states & cities
和只加载,状态我如何添加collection_select /选择何时选择了状态?
PS:加载状态和城市需要基于选择哪个国家和州。
有没有什么宝石我正在寻找或Ajax解决方案? (其他解决方案也赞赏)
这就是所谓的[级联下拉](https://www.google.com.br/search?q=cascading+dropdowns+in+rails&gws_rd=cr,ssl&ei=vTHQVvDHH4mowASrraTgAQ)。 – Mohamad
@ Mohamad Tnx,它是否仍然在页面加载或仅在选择国家和州时加载州和城市? – Rubioli
这取决于您的实施。我链接到谷歌搜索“在Rails级联下拉列表”,而不是一个特定的实现。看看一些链接,我相信你会找到一些这样做的好方法。 – Mohamad