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][team_name]">
Any ideas how to prefill this nested field?
build can be used for this in your controller (as it doesn't cause a
save on the
@user object), appending new
Team instances to the
:teams collection on the
@user object. In your action
@user = User.new @user.teams = [ Team.build(...) ]
... contains the default attributes for
@user.teams.first that will be displayed in the nested form.