0

在Ruby on rails中,我嘗試將數據保存在多個關係很多的表中。RoR:多級嵌套保存

我的模型看起來:

evid.rb:

class Evid < ActiveRecord::Base 
    attr_accessible :kod, :nazov, :okruh_id, :bank_ucets_attributes, :poc_stavs_attributes 
    #attr_accessible :ciselny_rads_attributes 

    has_many :ciselny_rads 
    has_many :bank_ucets, :foreign_key => :evidencia_id 
    has_many :poc_stavs, :foreign_key => :evidencia_id 

    accepts_nested_attributes_for :poc_stavs, :allow_destroy => true 
    accepts_nested_attributes_for :bank_ucets, :allow_destroy => true 
    #accepts_nested_attributes_for :ciselny_rads, :allow_destroy => true 
end 

bank_ucet.rb

class BankUcet < ActiveRecord::Base 
    attr_accessible :ciselny_rad_id, :evidencia_id 
    attr_accessible :ciselny_rad_attributes 

    belongs_to :ciselny_rad 
    belongs_to :evid, :foreign_key => "evidencia_id" 

    accepts_nested_attributes_for :ciselny_rad, :allow_destroy => true 

end 

ciselny_rad.rb

class CiselnyRad < ActiveRecord::Base 
    attr_accessible :evidencia_id, :kod, :nazov, :ciselny_rad_cislos_attributes 

    belongs_to :evid, :foreign_key => "evidencia_id" 
    has_many :ciselny_rad_cislos, :dependent => :delete_all 

    accepts_nested_attributes_for :ciselny_rad_cislos, :allow_destroy => true 
end 

poc_stav.rb

class PocStav < ActiveRecord::Base 
    attr_accessible :evidencia_id, :hosp_roky_id, :poc_stav 

    belongs_to :evid, :foreign_key => :evidencia_id 
end 

,我試圖將數據保存

@bank_ucet = Evid.create(data) 

data={ 
    "kod": "XX", 
    "nazov": "XxxXxUxXxxX", 
    "okruh_id": 5, 
    "bank_ucets_attributes": [ 
     { 
      "cis_banka_id": 1, 
      "cislo_uctu": 999999, 
      "cis_mena_id": 1, 
      "ciselny_rad_attributes": { 
       "kod": "XX", 
       "nazov": "XxxXxUxXxxX" 
      } 
     } 
    ], 
    "poc_stavs_attributes": [ 
     { 
      "hosp_roky_id": null, 
      "poc_stav": 1000 
     } 
    ] 
} 

一切都很正常,但唯一的問題是,在表ciselny_rad該evidencia_id填充空,而不是新創建的evid。

你能幫助我嗎? 感謝

回答

1

嘗試類似:

has_many :bank_ucets, :foreign_key => :evidencia_id, :inverse_of => :evid 

Evid類:

belongs_to :evid, :foreign_key => "evidencia_id", :inverse_of => :bank_ucets 
BankUcet

推理:在我使用嵌套屬性的經驗中,拋出inverse_of在這個地方及其周圍通常會排除任何問題。