AnthonyGalli.com AnthonyGalli.com - 4 months ago 14
Ruby Question

How to put nested fields_for code directly in parent _form?

How can I rewrite the code in

duels/_form
so I can put the code from
dueler_fields
directly in there?

duels/_form


<%= simple_form_for(@duel) do |f| %>
<%= f.text_field :consequence %>
<%= f.text_field :reward %>
<%= f.fields_for :duelers do |dueler| %>
<%= render 'dueler_fields', :f => dueler %>
<% end %>
<%= link_to_add_association f, :duelers do %>
<span class="glyphicon glyphicon-plus"></span> Dueler
<% end %>
<% end %>


_dueler_fields


# I want to place these two lines of code in the _form
<%= f.number_field :user_id, placeholder: "Enter User ID" %>
<%= f.number_field :challenge_id, placeholder: "Enter Challenge ID" %>


duels_controller


def new
@duel = Duel.new
respond_with(@duel)
end


duels
has_many
duelers
.

Answer

change f to dueler and you should be good to go. or:

<%= simple_form_for(@duel) do |f| %>
  <%= f.text_field :consequence %>
  <%= f.text_field :reward %>
  <%= f.fields_for :duelers do |dueler_form| %>
    <%= dueler_form.number_field :user_id, placeholder: "Enter User ID" %>
    <%= dueler_form.number_field :challenge_id, placeholder: "Enter Challenge ID" %>
  <% end %>
<% end %>