[英]How do I update a model object's associated object?
我想要像下面這樣的東西:
@user.update_attributes(:name => "Obama", :profile => { :current_location => 'US' })
用戶has_one個人資料。
使它們成為'嵌套屬性'。 文件說:
考慮具有一個頭像的會員模型:
class Member < ActiveRecord::Base
has_one :avatar
accepts_nested_attributes_for :avatar
end
...
允許您通過成員更新頭像:
params = { :member' => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
member.update_attributes params['member']
member.avatar.icon # => 'sad'
正如bjelli所說,這是你可能想要的accepts_nested_attributes_for
方法。 重要的是要注意它是傳遞profile的:id屬性,它允許它識別它是你要執行的更新。
我建議閱讀這個nested_attributes.rb注釋以了解更多:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.