【问题标题】:Dropdown not updating with updated data in Rails下拉菜单未使用 Rails 中的更新数据进行更新
【发布时间】:2018-08-21 13:36:53
【问题描述】:

我在 Rails 中遇到了选择选项的问题。在更改状态时,应该附加城市选项,但这对我不起作用。请帮帮我,那做错了什么

这就是我所做的: 在我的 _form.html.erb 文件中:

        <div class="form-group col-md-6">
          <!-- State -->
          <%= label_tag "Shop address" %>
          <%= select_tag :pstate, options_for_select(CS.states(:in).map { |c| [c[1], c[0]] }), class: "form-control", :required => true, :onchange => "stateChanged(event)" %>
        </div>

        <div class="form-group col-md-6">
          <!-- City -->
          <%= label_tag "Shop location" %>
          <%= select_tag :pcity, options_for_select([@pcities]), class: "form-control", :required => true %>
        </div>    
      </div>  

    <script>
       var stateChanged = function(e){
       $.ajax({
         url: "products/product_cities?state=" + e.target.value,
         type: "GET"
       })
     }
   </script> 

并且在 products_controller.rb 文件中

   def product_cities
         @pcities = CS.get(:in, params[:state])
         puts @pcities.inspect
       end

在 products_cities.js.erb 文件中

    <%# // Find the state select box %>
 var city = document.getElementById("pcity");
 console.log(city);
 <%# // Clear the options in the select box %>
 while (city.firstChild) city.removeChild(city.firstChild);

 <%# // Add a placeholder %>
 var placeholder = document.createElement("option");
 placeholder.text = "Choose a city";
 placeholder.value = "";
 city.appendChild(placeholder);

 <%# // Add the cities %>
 <% @pcities.each do |c| %>
     city.options[city.options.length] = new Option('<%= c %>');
 <% end %>

请你帮我摆脱困境。

【问题讨论】:

    标签: javascript ruby-on-rails ruby-on-rails-5


    【解决方案1】:

    变化:

    ...options_for_select([@pcities])...
    

    进入这个(不要忘记对两条线都这样做!):

    ...options_for_select([@pcities],@<<PUT YOUR MODEL HERE w/o BRACKETS>>.pcity)...
    

    这个可选的最后一个参数的作用是设置下拉列表的选定值(如果存在)。很方便。

    这是我自己使用选择助手的所有参数的示例:

    <%= f.select :state, options_for_select(us_states, @user.state), {:include_blank => "Select a state"}, {:class => "form-control"} %>
    

    :include_blank 本质上是一个占位符。希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2012-02-28
      • 2018-04-27
      • 2011-08-22
      • 2021-07-31
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多