1

几天来,我一直在挖掘国家和州/省选择的宝石。有些很棒(例如country-state-select)但不适合我的需要。

几乎强制性的country_select gem 很好,但缺少状态。不过是基于这个非常酷的宝石叫做国家。宝石国家确实为 300 多个国家/地区(包括 i18n)汇总了很多很好的信息,比如莫桑比克及其细分市场等等。

在应用程序中拥有国家宝石,所需要的只是一些与之交互的javascript。调用是这样的:

country = ISO3166::Country.new('US')

这是表格:

<%= simple_form_for(@order) do |f| %>
<div><%= f.input :country %></div>
<div><%= f.input :state %></div>
<%= f.button :submit, t('.submit') %>
<% end %>

<script type="text/javascript">
states_drop_down = $("#order_state");
$("#order_country").change(function() {

// How to make this work?
    <% unless params[:country].nil? %>
        states_drop_down.clearAttributes();
        <% ISO3166::Country.new(params[:country]).states.each do |state| %>
            states_drop_down.setAttribute(<%= state[:name] %>, <%= state[:alpha2] %>); // How to log to check if new attributes are present?
        <% end %>
        states_drop_down.reload(); // How to reload the state simple_form input?
    <% end %>
});

目标是已知的,每次国家下拉列表更改时,用正确的国家填充国家选择器。有什么帮助吗?谢谢。

4

1 回答 1

1

我找到了一个解决方案,即使不再使用宝石国家。数据被播种到数据库并从那里提取。在这里找到数据。

然后只需要几个步骤:

// 1. new action at controller, in my case was orders. This receives the calls and renders the views.
  def update_states
      country = Country.find(params[:nation_id])
      @states = country.states
      respond_to do |format|
        format.js
      end   
  end

// 2. new get at routes to find the new action
  get "orders/update_states", as: "update_states"

// 3. simple_form with collections. Note uses nation to avoid the simple_form country selector error.
  <%= simple_form_for(@order) do |f| %>
  <div><%= f.input :nation, collection: @countries %></div>
  <div><%= f.input :state, collection: @states %></div>
  <%= f.button :submit, t('.submit') %>
  <% end %>

// 4. new doc at app/views/states/_state.html.erb to render inside the dropdown selector.
  <option value="<%= state.id %>"><%= state.name %></option>

// 5. new lines at app/assets/javascripts/orders.js.coffee to listen to nation or country selector.
  $ ->
  $(document).on 'change', '#order_nation', (evt) ->
  $.ajax 'update_states',
  type: 'GET'
  dataType: 'script'
  data: {
    nation_id: $("#order_nation option:selected").val()
  }
  error: (jqXHR, textStatus, errorThrown) ->
    console.log("AJAX Error: #{textStatus}")
  success: (data, textStatus, jqXHR) ->
    console.log("State selection is working!")

// 6. and app/views/orders/update_cities.js.cofee, the piece that close the circle. This actually renders the info and views.
  $("#order_state").empty()
  .append("<%= escape_javascript(render(:partial => @states)) %>")

必须感谢 Kernel Garden,我在这里找到了我正在寻找的 javascript 。

于 2016-02-22T01:50:28.440 回答