ruby-on-railsrubyruby-on-rails-4fields-for

How to dynamically increment a counter inside fields_for?


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

Week 2

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.


Solution

  • 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 %>