2013-05-03 215 views
1

在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是一樣的收件人記錄但帶有新電子郵件。

回答

5

您需要傳遞要更新的嵌套屬性的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