Jerome
Jerome

Reputation: 6189

form to conditionally display fields based on array position

the following rails controller action, creates an array of records to be created:

  @guests = []
  @quantity.times do
    @guests << Guest.new
  end

Then the form invokes the array of records to be created in the following manner

<%= form_tag guests_path do %>
  <% @guests.each do |guest| %>
    <%= fields_for 'guests[]', guest do |f| %>

The goal is to render some fields only for the first of these records/

How can the index value of the first guest be invoked (various attempts such as if @guests[0] generate errors.

Upvotes: 0

Views: 30

Answers (1)

Holden Mitchell
Holden Mitchell

Reputation: 26

I think what you are looking for is each with index

<%= form_tag guests_path do %>
 <% @guests.each_with_index do |guest,index| %>
  # Do something with index
  <%= fields_for 'guests[]', guest do |f| %>

Upvotes: 1

Related Questions