1

在 Rails 中,update_attributes在模型上使用将创建基于association_attributes. 有没有一种惯用的方法来更新嵌套模型?

例如:

消息.rb:

attr_accessible :recipient_attributes
has_one :recipient
accepts_nested_attributes_for :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成为相同的收件人记录,但使用新电子邮件。

4

1 回答 1

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"}
于 2013-05-03T20:22:20.260 回答