Why are <input> element ID's repeating in nested form?
class User
has_one :user_profile
end
class UserProfile
belongs_to :user
end
I am rendering a form for editing using partials.
The views are:
user_profile/edit.html.erb
--------------------------
<%= render 'form开发者_C百科' %>
user_profile/_form.html.erb
---------------------------
<%= form_for @user_profile do |f| %>
<%= f.fields_for @user_profile do |builder| %>
<%= render :partial => 'user_profiles/fields', :locals => { :f => builder } %>
# id is correct i.e. [user_profile][last_name] for the field below
<%= f.text_field :last_name %>
<% end %>
<%= f.submit %>
<% end %>
user_profile/_fields.html.erb
-----------------------------
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
# id's for the above fields are rendered as:
# user_profile[user_profile][first_name]
# notice the second repeated [user_profile]
How do I fix it so that the id's come out as user_profile[first_name]
instead of user_profile[user_profile][first_name]
?
From the documentation for fields_for it's:
suitable for specifying additional model objects in the same form.
With an example showing this paradigm:
<%= form_for @person do |person_form| %>
First name: <%= person_form.text_field :first_name %>
Last name : <%= person_form.text_field :last_name %>
<%= fields_for @person.permission do |permission_fields| %>
Admin? : <%= permission_fields.check_box :admin %>
<% end %>
<% end %>
Notice form_for @person
and fields_for @person.permission
- fields_for should be used for an association of a model, form_for should be used for the model itself. The reason your html is rendering as user_profile[user_profile]
is that you're specifying @user_profile
in both form_for
and fields_for
.
You likely need to change the parameter in form_for
to @user (or the equivalent variable you have in scope). This will make your output html:
user[user_profile][first_name]
which you can pass to UsersController#update as long as User accepts_nested_attributes_for
user_profile. If you want to instead pass the parameter hash from the form to UserProfilesController#update, then you want to drop the fields_for
entirely and just render the fields under form_for @user_profile
- which will give you html like user_profile[first_name]
.
精彩评论