【问题标题】:How to select state based on country selection in rails?如何根据rails中的国家选择来选择国家?
【发布时间】:2015-11-02 06:35:39
【问题描述】:

我在 DB、Countrys 和 States 中有 2 个表。现在,当我根据选择选择国家时,它必须显示州。

对于 .rhtml 文件中的国家/地区选择,我使用如下:

<%= select_tag "User[country_id]", options_for_select(Country.all.collect{|x| [x.country,x.id]})%>

现在基于上述选择,我需要选择状态。

【问题讨论】:

    标签: html ruby-on-rails ruby web


    【解决方案1】:

    查看:

    <%= select_tag
      :country_select, # name of selectbox
      options_from_collection_for_select(@myrecords, "id", "name"), # your options for this select box
      :'data-remote' => 'true', # important for UJS
      :'data-url' => url_for(:controller => 'MyController', :action => 'getdata'), # we get the data from here!
      :'data-type' => 'json' # tell jQuery to parse the response as JSON!
    %>
    
    
    <%= select_tag
      :state_select, # name of selectbox
      "<option>Please select something from country select!</option>"
    %> 
    

    控制器:

    class MyController < ApplicationController
      def getdata
        # this contains what has been selected in the first select box
        @data_from_country_select = params[:country_select]
    
        # we get the data for selectbox 2
        @data_for_state_select = MyModel.where(:some_id => @data_from_country_select).all
    
        # render an array in JSON containing arrays like:
        # [[:id1, :name1], [:id2, :name2]]
        render :json => @data_for_state_select.map{|c| [c.id, c.name]}
      end
    end
    

    Javascript:

    $(document).ready(function() {
    
      // #country_select is the id of our first select box, if the ajax request has been successful,
      // an ajax:success event is triggered.
    
      $('#country_select').live('ajax:success', function(evt, data, status, xhr) {
        // get second selectbox by its id
        var selectbox2 = $('#state_select');
    
        // empty it
        selectbox2.empty();
    
        // we got a JSON array in data, iterate through it
    
        $.each(data, function(index, value) {
          // append an option
          var opt = $('<option/>');
    
          // value is an array: [:id, :name]
          opt.attr('value', value[0]);
          // set text
          opt.text(value[1]);
          // append to select
          opt.appendTo(selectbox2);
        });
      });
    
    });
    

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
    • 感谢您的建议,我将更新答案以仅包含重要部分。
    • 继续让它有意义
    • live('ajax:success', function(evt, data, status, xhr) is not working and raise an error. States data is not retrieve based on Country selection. Bootstrap errors are up by using这个。
    【解决方案2】:

    我个人从未尝试过这种方式,请在国家/地区下拉列表中尝试此代码。

    "f.select_tag :state, State.where(country_id: c.id)"
    
    
    <div class="field">
       <%= f.label :country %><br>
       <%= f.select :country_id, Country.all.map {|c| [c.name, c.id] }, {prompt:"Choose Country"} %>
    </div>
    

    【讨论】:

      【解决方案3】:

      您需要使用ajax 来获取更新后的states,如下所示:

      #config/routes.rb
      resources :countries do
         get :state, on: :member #-> url.com/countries/:country_id/states/
      end
      

      您必须将 states 操作添加到您的 countries 控制器:

      #app/controllers/countries_controller.rb
      class CountriesController < ApplicationController
         def states
            @country = Country.find params[:country_id]
            @states = @country.states
            respond_to do |format|
               format.json { render json: @states.to_json }
            end
         end
      end
      

      这将允许您在更改 select 的值时向该控制器发送 ajax 请求:

      #app/assets/javascripts/application.js
      $(document).on("change", "#countries", function(e){
         url = "countries/" + $(this).val() + "/states";
         $.get(url, function(data){
            $.each(data,function(key, value){
               $("#states").find('option').remove().end();
               $("#states").append('<option value=' + key + '>' + value + '</option>');
            });
         }, "json")
      });
      

      --

      您还需要确保您的表单格式正确。

      具体来说,您需要使用form_for 而不是form_tag

      <%= form_for @user do |f| %>
        <%= f.collection_select :country_id, Country.all, :id, :name %>
      <% end %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-01
        • 2011-08-16
        相关资源
        最近更新 更多