1

我有一個外鍵插入和刪除記錄用的has_many:通過關聯,其中關聯取決於兩個FKS

class Assoc << ActiveRecord::Base 
    belongs_to entity1 
    belongs_to entity2 
end 

class Entity1 << ActiveRecord::Base 
    has_many :assocs 
    has_many :entities2 :through=>:assocs 
end 

class Entity2 << ActiveRecord::Base 
    has_many :assocs 
    has_many :entities1 :through=>:assocs 
end 
創建2個重要的實體和關聯表

我看到這個問題how to add records to has_many :through association in rails,它似乎是合理的我除了這樣一個事實,他似乎可以創建一個Assoc實例,而不需要爲其分配Entity1和Entity2。這似乎不是我的情況。

在我的具體情況下,我正在處理物業和物業設施。關聯表只會鏈接一個屬性與許多屬性設施,反之亦然。 Assoc由2個fks定義,每個實體一個。

一旦我提交了一份表格,我現在正在採取行動。我已經獲得了Property並將其存儲在@property中。現在我想添加params[:property][:facility_ids](它的一個ID數組)的設施。

我該怎麼辦?

回答

0

可以完成刪除了dependent: destroy

class Entity1 < ActiveRecord::Base 
    has_many :assocs 
    has_many :entities2, through::assocs, dependent: :destroy 
end 

至於插入,你可以這樣做:

facility_ids = params[:property][:facility_ids] 
facility_array = [] 

facility_ids.each do |id| 
    facility_array << facility.find(id) 
end 

@property.facilities = facility_array 
+0

好吧,所以我必須做這個循環?我有一個關於刪除的問題。如果我想刪除該屬性中的一個設施,該怎麼辦?該設施將繼續在系統上,但該物業將不再有它(想象我沒有選中複選框,例如) –

+0

我正在尋找類似'Property.last.property_facilities.some_method_to_assign(facility_id:Facility.find( params [:facility_ids]))' –

+1

和我得到這個錯誤與您的代碼PropertyFacility(# - 648607518)預期,得到Facility(# - 651473278) –

0

您可以使用

@property.update_attributes property_facility_ids: (@property.property_facility_ids << params[:property][:facility_ids]) 

追加PropertyFacility協會,假設你的模型Propertyhas_many :property_facilities :through=>:assocs

以上只是將PropertyFacilityparams推到@property,您可以根據需要進行其他驗證。

相關問題