[英]How do I update a model object's associated object?
I want to something like the following: 我想要像下面这样的东西:
@user.update_attributes(:name => "Obama", :profile => { :current_location => 'US' })
where User has_one profile. 用户has_one个人资料。
Make them 'nested attributes'. 使它们成为'嵌套属性'。 The documentation says:
文件说:
Consider a Member model that has one Avatar: 考虑具有一个头像的会员模型:
class Member < ActiveRecord::Base
has_one :avatar
accepts_nested_attributes_for :avatar
end
... ...
allows you to update the avatar through the member: 允许您通过成员更新头像:
params = { :member' => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
member.update_attributes params['member']
member.avatar.icon # => 'sad'
As bjelli has stated it's the accepts_nested_attributes_for
method that you probably want here. 正如bjelli所说,这是你可能想要的
accepts_nested_attributes_for
方法。 It's important to notice that it is the passing in of the profile's :id attribute that allows it to recognize it's an update you want to peform. 重要的是要注意它是传递profile的:id属性,它允许它识别它是你要执行的更新。
I would recommend reading this the nested_attributes.rb comments to understand more : ) 我建议阅读这个nested_attributes.rb注释以了解更多:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.