I have a user model which has_one profile. The user model has a name attribute which is set when a user signs up. However, I want to let a user update that nam开发者_StackOverflowe attribute from the profile's edit view. How can I do this?
Nested attributes and the fields_for form helper are your friends.
class Profile < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end
That allows you to give nested user attributes to the profile:
ruby-1.9.2-p0 > params = { :profile => { :some_profile_attr => "some value", :user_attributes => { :name => "some_new_name" }}}
=> true
ruby-1.9.2-p0 > profile.update_attributes params[:profile]
=> true
ruby-1.9.2-p0 > profile.user.name
=> "some_new_name"
When you want to update the user attributes through the profile form you can use the fields_for form helper:
<%= form_for @profile do |profile_form| %>
[..]
<%= profile_form.fields_for :user do |user_form| %>
<%= user_form.text_field :name %>
<% end %>
[..]
<% end %>
精彩评论