2016-02-26 125 views
0

我有countries, states & cities数据库和他们的型号Country, State & CityRuby 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解决方案? (其他解决方案也赞赏)

+0

这就是所谓的[级联下拉](https://www.google.com.br/search?q=cascading+dropdowns+in+rails&gws_rd=cr,ssl&ei=vTHQVvDHH4mowASrraTgAQ)。 – Mohamad

+0

@ Mohamad Tnx,它是否仍然在页面加载或仅在选择国家和州时加载州和城市? – Rubioli

+0

这取决于您的实施。我链接到谷歌搜索“在Rails级联下拉列表”,而不是一个特定的实现。看看一些链接,我相信你会找到一些这样做的好方法。 – Mohamad

回答

1

你可以在rails中做到这一点,而不使用任何宝石。

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元素。

+0

Tnx,目前我没有国家,州和城市的控制器。是否需要先让他们? – Rubioli

+0

不需要。这不是强制性的,你可以继续使用你正在使用的控制器。但是,对于更好的实践,您可以在类名称下将类似的操作放在一起 – Bijendra