0
我有一個has_one配置文件的用戶模型。用戶模型具有用戶註冊時設置的名稱屬性。但是,我想讓用戶從配置文件的編輯視圖更新該名稱屬性。我怎樣才能做到這一點?如何從另一個關聯模型的視圖編輯模型的屬性
我有一個has_one配置文件的用戶模型。用戶模型具有用戶註冊時設置的名稱屬性。但是,我想讓用戶從配置文件的編輯視圖更新該名稱屬性。我怎樣才能做到這一點?如何從另一個關聯模型的視圖編輯模型的屬性
嵌套屬性和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 %>
你爲什麼給用戶形式的例子?我想編輯配置文件表單中的用戶屬性。我想我想要做的是你的例子,除了切換用戶和個人資料... – 2011-03-27 06:55:57
是的,對不起。沒有咖啡:-)我改變了它。 – 2011-03-27 07:13:00