两个集合选择形式

时间:2015-10-26 17:01:36

标签: ruby-on-rails ruby-on-rails-4

我有三个模特

City
belongs_to :country

Country
has_many :cities

User
belongs_to :city

在用户表单中我想做两个选择,第一个是选择一个国家

<%= f.collection_select :country_id, Country.all, :id, :name, options = {:prompt => 'Select a Country'}, html_options = {class:"form-control", required:true} %>

这对我来说很好。但问题是选择一个城市,我不知道如何只列出所选国家的城市。我读过有关grouped_collection_select但我无法解决我的问题。

我该怎么做?谢谢!

P.D:我不想使用宝石。

我使用grouped_collection_select

解决了这个问题
<%= f.grouped_collection_select :city_id, Pais.order(:name),:cities,:name, :id, :name, options = {:prompt => 'Select a City'}, html_options = {class:"form-control", required:true}%>

和jquery

$(function() {
    filterCitiesList();
})
function filterCitiesList() {
    $('#user_city_id').hide();
    users = $('#user_city_id').html();
    $('#user_country_id').change(function() {
        country_id = $('#user_country_id :selected').text();
        optgroup = "optgroup[label='" + country_id + "']"
        options = $(cities).filter(optgroup).html();

        if (country_id != "Select Country") {
            $('#user_city_id').show();
            $('#user_city_id').html(options);
        }
        else{
            $('#user_city_id').hide();
        }
    });
}

现在我有另一个问题。我是模态窗口,当我隐藏国家模式时,我使用

<%= select_tag "countries",options_from_collection_for_select(Country.all, "id", "name"), {id:"user_country_id", name:"user[country_id]",include_blank: 'Select Country', class: "form-control"}%>

以呈现国家/地区选择。新的问题是我如何使用grouped_collection_select?

我使用option_groups_from_collection_for_select

解决了这个问题
<%= select_tag "cities",option_groups_from_collection_for_select(Country.order(:name), :cities, :name, :id, :name), {id:"user_city_id", name:"user[city_id]",include_blank: 'Select City', class: "form-control"} %>

感谢您的回答!

1 个答案:

答案 0 :(得分:1)

您可以尝试使用Ajax和Javascript解决此问题。

  1. 用户选择一个国家/地区。
  2. 将所选国家/地区ID发送到服务器。
  3. 按国家/地区ID获取相应的城市。
  4. 使用新结果刷新城市选择。
  5. 这是基本的想法。

相关问题