如何从其他相关的模型视图编辑模型的属性 [英] How to edit a model's attribute from the view of another associated model

查看:133
本文介绍了如何从其他相关的模型视图编辑模型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户模式,HAS_ONE轮廓。用户模型具有当用户注册设置的名称属性。不过,我想让那名从配置文件的编辑视图属性的用户更新。我怎样才能做到这一点?

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?

推荐答案

嵌套属性和的 fields_for 形式的帮手是你的朋友。

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"

当您要更新用户通过您可以使用fields_for表单辅助配置文件表单属性:

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

这篇关于如何从其他相关的模型视图编辑模型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆