ActiveRecord对由新集合替换的关联进行回调

时间:2010-11-22 23:18:50

标签: ruby-on-rails activerecord callback

对于从关系集合中删除期间更新的对象的回调似乎并没有为我执行。

我有一个模型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

对于这个例子,我们假设我有一个带有“Locations”集合的“Thing”,由my_thing.locations引用。这将返回Zip,地址等的集合。

如果我写代码

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

然后按预期创建一个新的EntityLocation,可以从my_thing.locations中准确引用。但问题是以前包含在此集合中的记录现在在数据库中以孤立的entity_id属性孤立。我试图在after_save回调中删除这些对象,但它永远不会在旧对象上执行。

我也尝试过使用after_update,而after_remove并没有在旧记录上调用。新创建的记录after_save回调确实按预期调用,但这对我没有帮助。

Rails是否在不通过活动记录执行回调链的情况下更新先前引用的对象?所有想法都赞赏。谢谢。

1 个答案:

答案 0 :(得分: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

现在从任一方删除也会删除连接表行。