Nested_attributes 找不到两个嵌套的导轨



我有一个问题,我正在保存一个具有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}}

这个例子只保存作者的书

我该如何解决这个问题?

我有同样的问题,我不能用一个好的方法解决。我不知道为什么,但是在保存之前,似乎地址的属性正在丢失。我这样做了:

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

注意,这本书验证了地址的属性,但当将保存地址时,似乎他丢失了参数。

最新更新