我正面临着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 %>
您能帮我摆脱这个问题吗?
答案 0 :(得分:0)
更改:
...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
本质上是一个占位符。希望这会有所帮助!