How to dynamically increment a counter inside fields_for?

410 Views Asked by At

I am building a form where someone can add daily challenges through a form. This form should list the items for each day of the week vertically. These days should be grouped by week #.

In this manner:

Week 1

  • Challenge #1
  • Challenge #2
  • Challenge #3

Week 2

  • Challenge #4
  • Challenge #5
  • Challenge #6

I use a button to add items dynamically and the incrementing should happen when these items are added too. After 7 daily challenges within a week, a new week section should be created on the UI.

I've used fields_for and tried using a simple counter, incrementing it within each iteration.

<% i = 1 %>

<div id="challenges_container">
<%= f.fields_for :challenges do |mi| %>
<% i += 1 %>
<%= i %>

<% end %>
</div>

<p><%= f.link_to_add '<i class="fi-plus"></i> Add Challenge'.html_safe, :challenges, :data => {:target => '#challenges_container'} %></p>

I expected the 'i' counter to be incrementing by one every time I click on the 'Add Challenge' button but it only gets set to '2' when I load the page initially.

2

There are 2 best solutions below

0
Mark On BEST ANSWER

You should take a look at: Rails: fields_for with index?

In your case, try:

<% @challenges.each_with_index do |challenge, index| %>
  <%= f.fields_for :challenges, challenge do |fc| %>
  ## Do whatever you want with challenge and index
  <% end %>
<% end %>
0
Denis Lessard On

The solution that Mark has pointed out does work fine to get the indexes of items at first load. For anyone looking into making it work dynamically, I had to use Javascript. You can find more info about it here: Javascript events That way you can manipulate the DOM even after it's loaded (for adding new elements, for example).