Justin Meltzer
Justin Meltzer

Reputation: 13548

How to edit a model's attribute from the view of another associated model

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 name attribute from the profile's edit view. How can I do this?

Upvotes: 0

Views: 1061

Answers (1)

Julian Maicher
Julian Maicher

Reputation: 1793

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 %>

Upvotes: 2

Related Questions