【发布时间】:2013-09-24 09:42:55
【问题描述】:
我的问题与this 几乎相似。只是略有不同。
我有两个模型 - Family 和 Person,has_many from family to person 和 accepts_nested_attributes_for :persons in family.rb
在我的 FamiliesController 中,我有 edit 编辑记录的方法。我正在为一个家庭和相应的人使用 嵌套表单。 (所以一个家庭可以有很多人)
在我的 edit.html.erb 中,我的表单如下:
<%= simple_form_for @family do |f| %>
#family fields here
<%= f.simple_fields_for :persons do |p| %>
<%= p.input :gender,as: :radio_buttons,collection: ["Male","Female"],wrapper_html: {id: "gender"} %>
<%= p.input :question,wrapper_html: {id: "question"} %>
<% end %>
<%= f.submit "Submit" %>
<% end %>
(类似于链接中的问题)
我应用了与答案中提到的相同的 javascript。 (here)
$(function(){
var toggle_gender = function(visible) {
if (visible){
$("#question").show();
} else {
$("#question").hide();
}
}
$("#gender input").change(function(){
toggle_gender($(this).val()=="Male")
})
toggle_gender($("#gender input:checked").val()=="Male")
})();
生成的 HTML:
<div class="control-group radio_buttons required family_persons_gender gender">
<label class="radio_buttons required control-label">
<abbr title="required">*</abbr>
Gender
</label>
<div class="controls">
<label class="radio">
<input id="family_persons_attributes_1_gender_male" class="radio_buttons required" type="radio" value="Male" name="family[persons_attributes][1][gender]" checked="checked">
Male
</label>
<label class="radio">
<input id="family_persons_attributes_1_gender_female" class="radio_buttons required" type="radio" value="Female" name="family[persons_attributes][1][gender]">
Female
</label>
</div>
</div>
<div class="control-group string required family_persons_mobnum mobnum">
<label class="string required control-label" for="family_persons_attributes_1_mobnum">
<abbr title="required">*</abbr>
Mobile No.
</label>
<div class="controls">
<input id="family_persons_attributes_1_mobnum" class="string required" type="text" value="9099067758" size="50" name="family[persons_attributes][1][mobnum]">
</div>
</div>
但这只适用于第一人称。含义如果我有 1 个家庭和 3 个人,则 javascript 仅适用于第一个人。为什么这样?
含义如果有 2 个人并且我改变了第二个人的性别,那么 javascript 适用于第一个人而不是第二个人
我该如何解决这个问题?
我在某处读到使用 迭代 javascript(有些人甚至说 underscore.js)。
或建议任何替代方法
【问题讨论】:
标签: javascript jquery ruby-on-rails nested-forms simple-form