Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to iterate inside a simple_fields_for?

I need to iterate inside the simple_fields_for block to assign a number [0 to 6] to the :day field.

Controller

7.times { @doctor.schedules.build }

View

<tr>
    <% @i = 0 %>
    <%= f.simple_fields_for :schedules do |builder| %>
    <td>
    <%= builder.input :day, value: @y, wrapper: :check  %>
    <%= builder.input :is_available, as: :boolean, label: false, wrapper: :check %>
    <% @i += 1 %>
    </td>
<% end %>
</tr>

obviously this will start from 1 until 7, how can I make it iterate from 0 to 6?

like image 719
evanx Avatar asked Jan 22 '13 21:01

evanx


2 Answers

JFYI, you'll be able to get current index in Rails 4. See this merged pull request

For now you can use something like this:

<% @doctor.schedules.each_with_index do |schedule, index| %>
  <%= f.simple_fields_for :schedules, schedule do |ff| %>
    <%= ff.input :day, value: index %>
  <% end %>
<% end %>
like image 97
Vasiliy Ermolovich Avatar answered Sep 23 '22 01:09

Vasiliy Ermolovich


Like mentioned it is possible in Rails 4 after the merge https://github.com/rails/rails/pull/5746. In Rails 4 you can use .index on the 'builder':

<%= f.simple_fields_for :schedules do |builder| %>
  <%= builder.input :day, value: builder.index+1 %>
<% end %>
like image 28
joost Avatar answered Sep 27 '22 01:09

joost