当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - How to prefill nested form fields

问题描述:

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 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(...) ]

where ... contains the default attributes for @user.teams.first that will be displayed in the nested form.

分享给朋友:
您可能感兴趣的文章:
随机阅读: