Rails ActiveRecord更新嵌套属性

时间:2013-05-03 20:14:08

标签: ruby-on-rails activerecord nested-attributes idioms

在rails中,在模型上使用update_attributes将基于association_attributes创建嵌套模型。是否有一种惯用的方法来使其更新嵌套模型?

例如:

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: "john@gmail.com"
r.update_attributes recipient_attributes: {email: "johns_new_address@gmail.com"}
r.recipient.name # nil  <-- this creates a NEW recipient, so the name is nil
r.recipient.email # johns_new_address@gmail.com 

相反,我希望r.recipient成为相同的收件人记录,但需要新的电子邮件。

1 个答案:

答案 0 :(得分:5)

您需要传递嵌套属性的ID才能更新。如果没有ID,它会假设一个新的记录。

实际上,当然,它将是一种形式。但是,举个例子:

john = r.create_recipient name: "John Smith", email: "john@gmail.com"
r.update_attributes recipient_attributes: {id: john.id, email: "johns_new_address@gmail.com"}