我正在尝试进行动态选择,就像这样http://railscasts.com/episodes/88-dynamic-select-menus-revised?view=asciicast
在我的情况下,它不会以某种方式工作。
我的代码出了什么问题?
视图/注册/ edit.html.erb
<h2>Edit <%= resource_name.to_s.humanize %></h2>
<% resource.build_user_profile if resource.user_profile.nil? %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put, :class => 'form-horizontal' }) do |f| %>
<%= devise_error_messages! %>
<%= f.fields_for :user_profile do |profile_form| %>
<%= profile_form.label :country_id %><br />
<%= profile_form.collection_select :country_id, Country.all, :id, :name, include_blank: true %>
<%= profile_form.label :prefecture_id, "State or Prefecture" %><br />
<%= profile_form.grouped_collection_select :prefecture_id, Country.all, :prefectures, :name, :id, :name, include_blank: true %>
<% end %>
<br />
<div class="control-group">
<div class="controls">
<%= f.submit 'Update', :class => 'btn btn-primary' %>
</div>
</div>
<% end %>
user_profiles.js.coffee
jQuery ->
$('#user_profile_prefecture_id').parent().hide()
states = $('#user_profile_prefecture_id').html()
console.log(prefectures)
$('#user_profile_country_id').change ->
country = $('#user_profile_country_id :selected').text()
escaped_country = country.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
options = $(prefectures).filter("optgroup[label=#{escaped_country}]").html()
console.log(options)
if options
$('#user_profile_prefecture_id').html(options)
$('#user_profile_prefecture_id').parent().show()
else
$('#user_profile_prefecture_id').empty()
$('#user_profile_prefecture_id').parent().hide()
答案 0 :(得分:2)
在任何情况下,当你通过:
<%= f.fields_for :user_profile ... %>
当父表单构建器具有对象时,字段的属性 name = 和 id = 不能只是“#user_profile ...”。要确定ID,请查看源代码(HTML响应)。