0

比如我有這些模型:如何保存具有嵌套屬性的多態模型的belongs_to關聯?

class Person < ActiveRecord::Base 
    # attributes: id, name 
    has_one :address, as: :addressable 
    accepts_nested_attributes_for :address 
end 

class Company < ActiveRecord::Base 
    # attributes: id, name, main_address_id 
    has_one :address, as: :addressable 
    belongs_to :main_address, class_name: 'Address', foreign_key: :main_address_id 

    accepts_nested_attributes_for :main_address 

    def main_address_attributes=(attributes) 
    puts '='*100 
    puts attributes.inspect 
    self.build_main_address(attributes) 
    self.main_address.addressable_id = self.id 
    self.main_address.addressable_type = self.class.to_s 
    puts self.inspect 
    puts self.main_address.inspect 
    end 
end 

class Address < ActiveRecord::Base 
    # attributes: id, address1, address2, city_id,.. 
    belongs_to :addressable, polymorphic: true 
    validates :addressable_id, :addressable_type, presence: true 
end 

我試圖挽救Company與嵌套屬性,你可以假設這爲PARAMS:

{"name"=>"Test Company", "email"=>"", "display_name"=>"Company pvt ltd", "description"=>"Company desc", "founded_in"=>"2014-08-05", "website"=>"", "main_address_attributes"=>{"address1"=>"My address1", "address2"=>"My address2", "city_id"=>"10"}} 

這不工作,因爲它拒絕並且在可尋址時不存儲數據(addressable_idaddressable_type)爲main_address不存在,即使當我試圖在Company類的main_address_attributes=(attributes)方法中添加它時。

每當我試圖挽救這與上述PARAMS我得到這個錯誤:

Main address addressable can't be blank 

我該如何解決這個問題?

+0

你想保存'company'這是相關到'地址'(通過'main_address_id'),該地址通過'addressab返回到另一個地方('Company'或'Person') le'? – IS04 2014-08-31 17:12:13

+0

不,「Company」有兩個獨立的地址,一個是主地址,另一個是可選地址,「Person」可以有一個地址,但不在話題中。我需要的是將main_address_id保存爲創建的'Address'id,並指向創建的'Company'的可尋址方式。我希望有所幫助。 – Surya 2014-08-31 17:17:01

+0

在這種情況下,你應該使用相同的'多態'關係(否則你會得到一些關於我上面寫的東西) – IS04 2014-08-31 17:24:36

回答

0

萬一有belongs_to你會碰到這樣的:company相關address(通過main_address_id),它的回報是通過多態addressable與另一個(CompanyPerson)。

至於例如,你可以改變:

has_one :address, as: :addressable 

到:

has_many :address, as: :addressable 

,然後添加到您的Address

enum address_type: [:primary, :secondary] 
+0

我覺得這是唯一的選擇,謝謝! – Surya 2014-09-03 16:16:26

相關問題