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

假装没事ソ 提交于 2019-12-11 18:47:30

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/5447651/how-to-edit-a-models-attribute-from-the-view-of-another-associated-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!