如何更新ActiveRecord及其“has_and_belongs_to_many”相关对象

时间:2015-09-06 12:57:09

标签: ruby-on-rails activerecord

假设我有简单的2个相关模型:

class User < ActiveRecord::Base
  has_and_belongs_to_many :emails
  accepts_nested_attributes_for :emails
end

class Email < ActiveRecord::Base
  has_and_belongs_to_many :users
end

如果我更改其电子邮件数组,用户的实例如何更新:

@user = User.new(username: "ben", password: "ben123")
@user.emails.build(:address: "ben@email.com", app: "outlook")
@user.save!
@user.update(password: "321neb", emails: [{id: 1, app: "gmail"}])

更新行对我不起作用,那么更新的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您必须使用attributes表示您正在更新嵌套模型

@user.update(password: "321neb", emails_attributes: [{id: 1, app: "gmail"}])