我想要做的是点击index + 1
时显示值link_to_add
("添加日期"按钮)。
edit.html.erb
<div class="row">
<div class="col-md-12">
<%= simple_nested_form_for(@schedule) do |f| %>
<%= render 'schedule_form', f: f %>
<%= f.link_to_add "Add day", :rooms, data: {target: '#room'}, class: "btn btn-primary" %>
<%= f.submit "Edit my schedule", class: "btn btn-primary" %>
<% end %>
</div>
</div>
_schedule_form_html.erb
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control' %>
<div id="room">
<%= f.simple_fields_for :rooms do |a| %>
<p><b>Day <%= a.index.to_i + 1 %></b></p>
<%= a.input :room %>
<% end %>
</div>
当我点击link_to_add
时,始终会显示Day 1
。
单击link_to_add
时是否可以增加索引?
或者,如果你能给我另一种解决方案,我们将不胜感激。
解决!
edit.html.erb
添加javascript。
<div class="row">
<div class="col-md-12">
<%= simple_nested_form_for(@schedule) do |f| %>
<%= render 'schedule_form', f: f %>
<%= f.link_to_add "Add day", :rooms, data: {target: '#room'}, class: "btn btn-primary" %>
<%= f.submit "Edit my schedule", class: "btn btn-primary" %>
<% end %>
<script type="text/javascript">
$(document).on('nested:fieldAdded', function() {
var count = $('.day-number-element-selector').length;
//alert(count)
$('.day-number-element-selector').last().html(count).prepend("Day ").wrap("<b></b>");
});
</script>
</div>
</div>
_schedule_form_html.erb
添加class =&#34; day-number-element-selector&#34;。
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control' %>
<div id="room">
<%= f.simple_fields_for :rooms do |a| %>
<p class="day-number-element-selector"><b>Day <%= a.index.to_i + 1 %></b></p>
<%= a.input :room %>
<% end %>
</div>
答案 0 :(得分:1)
嵌套表单会发送您使用data-target
指定的元素的蓝图,其余部分由客户端处理。每次添加或删除对象时都会触发these个便捷事件。所以你可以使用javascript,如下所示:
$(document).on('nested:fieldAdded', function() {
count = $('day-number-element-selector').length;
$('day-number-element-selector').last().html(count);
});