I have a simple nested form using the ‘nested_form’ gem.
It looks like this:
<%= nested_form_for @user do |f| %>
<%= f.text_field :username, :size => 25 %>
<%= f.fields_for :teams do |team_form| %>
<%= team_form.label :team_name, 'Name of your team' %>
<% end %>
<%= f.submit :value =>'submit' %>
<% end %>
Now I want to prefill the fields in my new-action. While it’s easy to fill the username-field with @user.username = "someone" I have no idea how to access the first nested field “team_name” in the nested “team_form”.
In the html the field looks like this:
<input id="user_teams_attributes_0_team_name" type="text" name="user[teams_attributes][0][team_name]">
Any ideas how to prefill this nested field?
Typically
buildcan be used for this in your controller (as it doesn’t cause asaveon the@userobject), appending newTeaminstances to the:teamscollection on the@userobject. In your actionwhere
...contains the default attributes for@user.teams.firstthat will be displayed in the nested form.