2010-11-22 41 views
0

從關係集合中刪除期間更新的對象的回調似乎並未爲我執行。由新集合取代的關聯上的ActiveRecord回調

我有一個模型EntityLocation作爲實體(用戶/場所/事物)和位置(拉鍊,地址,鄰里)之間的多態關係。

class EntityLocation < ActiveRecord::Base 
    belongs_to :entity, :polymorphic => true 
    belongs_to :location, :polymorphic => true 

    def after_save 
    if entity_id.nil? || location_id.nil? 
     # Delete me since I'm no longer associated to an entity or a location 
     destroy 
    end 
    end 
end 

在這個例子中,讓我們假設我有一個「物」與「位置」,通過引用my_thing.locations的集合。如果我寫的代碼

my_thing.locations = [my_thing.locations.create(:location => Zip.find(3455))] 

則如預期新EntityLocation創建並可以從my_thing.locations準確地引用這將返回郵編,地址等

的集合。然而,問題是之前包含在這個集合中的記錄現在在數據庫中被孤立了一個nil entity_id屬性。我試圖在after_save回調中刪除這些對象,但是它永遠不會在舊對象上執行。

我也嘗試過使用after_update和after_remove,並且都沒有在舊記錄中調用。新創建的記錄after_save回調按預期的方式被調用,但這對我沒有幫助。

是否Rails更新先前引用的對象而不執行通過活動記錄的回調鏈?所有的想法都讚賞謝謝。

回答

0

爲什麼這需要多態?看起來你可以簡單地使用has_many :through來模擬多對多的關係。

其次,爲什麼不簡單地通過與:dependent => :destroy的關聯刪除連接錶行?那麼你不需要自定義回調

class Entity < ActiveRecord::Base 
    has_many :entity_locations, :dependent => :destroy 
    has_many :locations, :through => :entity_locations 
end 

class EntityLocation < ActiveRecord::Base 
    belongs_to :entity 
    belongs_to :location 
end 

class Location < ActiveRecord::Base 
    has_many :entity_locations, :dependent => :destroy 
    has_many :entities, :through => :entity_locations 
end 

現在從任何一方刪除刪除連接錶行也是如此。

+0

謝謝。它是多態關係的原因是因爲沒有類實體,也沒有類位置。實體是用戶,地點或事物的實例。位置是Zip,地址或鄰域的實例。因此,EntityLocation模型是多態的,它具有entity_type,entity_id,location_type和location_id字段。 儘管如此,我想完成你描述的行爲,儘管它是多態的。也許我只是錯過了正確的Rails語法? – thedob 2010-11-24 13:36:28