我有一个问题,我正在使用2个nested_attributes保存一个对象,但是它只保存第二个nested_attributes,如果我返回并更新第一个nested_attributes,它会正确保存。一个属性有has_many
和另一个has_one
,它一次只保存一个。
例如:
class Author
has_many :books
has_one :address
accepts_nested_attributes_for :books
accepts_nested_attributes_for :address
end
Params:
author: {books_attributes: {"0" => {title: "Title Test", id: 1}}, address_attributes: {city: "São Paulo", id: 2}}
此示例仅保存作者的书籍
我该如何解决这个问题?
答案 0 :(得分:2)
我有同样的问题,我无法以一种好的方式解决。我不知道为什么,但在保存之前,似乎地址的属性正在丢失。我这样做了:
class Author
has_many :books
has_one :address
accepts_nested_attributes_for :books
accepts_nested_attributes_for :address
before_save :build_address_object
after_save :save_address_object!
private
def build_address_object
@address = address
end
def save_address_object!
return unless @address
@address.author = self
@address.save
end
end
请注意,该书验证了地址的属性,但是何时保存地址,似乎他失去了参数。