tx291
tx291

Reputation: 1331

Listing attributes in fields_for in Rails form

I have a form_for, which encloses fields_for for a Party and Guest model (a party has many guests, accepts nested attributes for guests), and a guest belongs to a party. I have a form_for my Party model, that lists out certain fields for each guest in the party. My form works just fine, but I want to simply list the name of each guest in the form, so it appears:

"Bob"
   attending: yes || no
   meal choice: chicken || veggie || pasta

"Susie"
  attending: yes || no
  meal choice: chicken || veggie || pasta

Right now, what I have is just:

attending: yes || no
meal choice: chicken || veggie || pasta

attending: yes || no
meal choice: chicken || veggie || pasta

How can I just list out the guest.first_name for each iteration of the fields_for??? Clearly, my guests_form.first_name does not work.

The code for my form is:

people in your party:

<%= form_for @party do |f| %>

  <%= f.hidden_field :party_id, value: current_party.id %>
  <%= f.fields_for @guests do |guests_form| %>

  <%= guests_form.first_name %>
        <%= guests_form.label :attending, "attending?" %>
        <%= guests_form.radio_button :attending, true, :checked => true %>
        <%= guests_form.label :attending, "yes!", :value => true %>
        <%= guests_form.radio_button :attending, false, :checked => false %>
        <%= guests_form.label :attending, "no", :value => false %>

        <%=guests_form.label :meal_id, "meal choice" %>
        <%=guests_form.radio_button :meal_id, :checked => 1 %>
        <%= guests_form.label :meal_id, "chicken", :value => 1 %>
        <%=guests_form.radio_button :meal_id, :checked => 2 %>
        <%= guests_form.label :meal_id, "veggie", :value => 2 %>
        <%=guests_form.radio_button  :meal_id, :checked => 3 %>
        <%= guests_form.label :meal_id, "pasta", :value => 3 %>
    <%end%>

 <%= f.submit "submit", class: 'btn btn-primary btn-lg' %>

<%end%>

I've never used fields_for before, so any help would be much appreciated!!

Upvotes: 0

Views: 108

Answers (1)

Tom Connolly
Tom Connolly

Reputation: 694

You're using Devise? If yes, then:

<% if user_signed_in? %>
  <p>Hello <%= current_user.first_name %>, let us know your preferences:      </p>
<%form_for @party do...
...
...

  <% end %>
<% end %>

You'll need to capture the user_id in a hidden field so it is saved along with the selections. And I would consider using checkboxes or radio buttons from collection.

Upvotes: 1

Related Questions