Ruby on rails 对由新集合替换的关联的ActiveRecord回调

Ruby on rails 对由新集合替换的关联的ActiveRecord回调,ruby-on-rails,activerecord,callback,Ruby On Rails,Activerecord,Callback,从关系集合中删除时更新的对象上的回调对我来说似乎没有执行 我有一个模型EntityLocation,它充当实体(用户/地点/事物)和位置(拉链、地址、社区)之间的多态关系 然后,正如预期的那样,创建了一个新的EntityLocation,可以从my_thing.locations准确地引用它。但是,问题是以前包含在此集合中的记录现在在数据库中是孤立的,并且具有nil entity_id属性。我试图在after_save回调中删除这些对象,但是它永远不会在旧对象上执行 我还尝试使用after_更新

从关系集合中删除时更新的对象上的回调对我来说似乎没有执行

我有一个模型EntityLocation,它充当实体(用户/地点/事物)和位置(拉链、地址、社区)之间的多态关系

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

我还尝试使用after_更新,以及after_删除,并且在旧记录上都没有调用。保存回调后新创建的记录确实按预期被调用,但这对我没有帮助


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

为什么这需要多态性?似乎您可以简单地使用
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
类实体:销毁
有多个:位置,:到=>:实体\u位置
终止
类EntityLocation:销毁
有多个:实体,:至=>:实体\u位置
终止

现在,从任意一侧删除也会删除联接表行。

谢谢。它是多态关系的原因是因为没有类实体,也没有类位置。实体是用户、地点或事物的实例。位置是Zip、地址或邻居的实例。因此EntityLocation模型是多态的,因为它具有实体类型、实体id、位置类型和位置id字段。尽管如此,我还是希望实现您描述的行为,尽管它是多态的。也许我只是缺少正确的Rails语法?看起来你想要“双面多态性”,就我所知,如果不对Rails本身进行一些黑客攻击,这是不可能的。您应该看看has\u many\u polymorphs gem:。我不确定它是否为Rails3更新,但它可能会有所帮助。
my_thing.locations = [my_thing.locations.create(:location => Zip.find(3455))]
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