在 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
成为相同的收件人记录,但使用新电子邮件。