Rails ActiveRecord更新嵌套属性

问题描述:

在rails中,在模型上使用update_attributes将创建基于association_attributes的嵌套模型。有没有一种惯用的方式来更新嵌套模型?Rails ActiveRecord更新嵌套属性

例如:

Message.rb:

attr_accessible :recipient_attributes 
has_one :recipient 
accepts_nested_attributes_for :recipient 

Recipient.rb

belongs_to :message 
# has an name fied 
# has an email field 

收件人

r = Recipient.create 
r.create_recipient name: "John Smith", email: "[email protected]" 
r.update_attributes recipient_attributes: {email: "[email protected]"} 
r.recipient.name # nil <-- this creates a NEW recipient, so the name is nil 
r.recipient.email # [email protected] 

相反,我希望r.recipient是一样的收件人记录但带有新电子邮件。

您需要传递要更新的嵌套属性的ID。在没有身份证的情况下,它会呈现新的记录。

实际上,它当然是一种形式。然而,对于你的例子,但是:

john = r.create_recipient name: "John Smith", email: "[email protected]" 
r.update_attributes recipient_attributes: {id: john.id, email: "[email protected]"} 
+0

哦,这样做有很多的意义 - 如果我一直在使用has_many关联,那就显而易见了。谢谢! – 2013-05-03 20:27:18

+0

如果我可以+100这个,我会的。一个有趣的推论是我正在使用一个API,所以这还没有在表单中。如果它存在,我必须推断它并将其添加到参数中 – Mizmor 2017-03-30 20:36:19