Rails ActiveRecord更新嵌套属性

She*_* Yu 1 activerecord idioms ruby-on-rails nested-attributes

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

例如:

Message.rb:

attr_accessible :recipient_attributes
has_one :recipient
accepts_nested_attributes_for :recipient
Run Code Online (Sandbox Code Playgroud)

Recipient.rb

belongs_to :message
# has an name fied
# has an email field
Run Code Online (Sandbox Code Playgroud)

接受者

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 
Run Code Online (Sandbox Code Playgroud)

相反,我希望r.recipient收到相同的收件人记录,但会收到一封新电子邮件.

Nik*_*mov 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"}
Run Code Online (Sandbox Code Playgroud)