【问题标题】:How to edit a model's attribute from the view of another associated model如何从另一个关联模型的视图中编辑模型的属性
【发布时间】:2011-03-27 06:36:30
【问题描述】:

我有一个拥有个人资料的用户模型。用户模型具有在用户注册时设置的名称属性。但是,我想让用户从配置文件的编辑视图中更新该名称属性。我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 model associations


    【解决方案1】:

    嵌套属性和fields_for 表单助手是您的朋友。

    class Profile < ActiveRecord::Base
      belongs_to :user
      accepts_nested_attributes_for :user
    end
    

    这允许您为配置文件提供嵌套用户属性:

    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 表单助手:

    <%= form_for @profile do |profile_form| %>
      [..]
      <%= profile_form.fields_for :user do |user_form| %>
        <%= user_form.text_field :name %>
      <% end %>
      [..]
    <% end %>
    

    【讨论】:

    • 你为什么要举一个用户表单的例子?我想在配置文件表单中编辑用户属性。我想我想做的是你的例子,除了切换用户和个人资料......
    • 是的,很抱歉。还没喝咖啡:-) 我换了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2011-07-04
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多