使用accepts_nested_attributes_for时after_remove回调未触发问题排查
Rails嵌套属性删除关联时未触发after_remove回调问题
我定义了如下Post模型:
class Post < ApplicationRecord has_many :comments, after_add: :soil, after_remove: :soil, dependent: :destroy attr_accessor :soiled_associations accepts_nested_attributes_for :comments, allow_destroy: true def soil(record) self.soiled_associations = [record] end end
在视图中添加新comment时,对象会被加入post.soiled_associations属性(soiled_associations是我自定义的类似Rails Dirty类的关联状态追踪属性)。但在视图中删除comment时,post.soiled_associations属性并未添加对应对象。我怀疑这与accepts_nested_attributes_for的工作机制有关(可能绕过了这些回调),请问我哪里操作错了?
这是因为accepts_nested_attributes_for处理_destroy参数时,并不会通过remove方法移除关联对象,而是直接在数据库层面标记/执行删除操作,因此不会触发after_remove回调。
可以通过以下两种方式解决:
方式一:手动触发回调
重写comments_attributes=方法,在处理删除逻辑时主动调用追踪方法:
class Post < ApplicationRecord has_many :comments, after_add: :soil, dependent: :destroy attr_accessor :soiled_associations accepts_nested_attributes_for :comments, allow_destroy: true def soil(record) self.soiled_associations ||= [] self.soiled_associations << record end def comments_attributes=(attributes) # 筛选出标记为删除的comment ID deleted_ids = attributes.values .select { |attr| attr[:_destroy] == '1' } .map { |attr| attr[:id] } .compact # 找到对应对象并触发soil方法 comments.find(deleted_ids).each { |comment| soil(comment) } # 执行原嵌套属性处理逻辑 super end end
方式二:在关联模型添加销毁回调
在Comment模型上设置before_destroy回调,反向通知Post对象:
class Comment < ApplicationRecord belongs_to :post before_destroy :notify_post_soil private def notify_post_soil post.soil(self) if post.present? end end
注:这种方式会在所有销毁Comment的场景触发,如果需要仅限制嵌套属性删除的场景,需额外添加上下文判断。
另外注意:你当前的soil方法每次赋值都会覆盖数组,若需要追踪多个关联对象,应改成追加逻辑(如上面代码中修改后的写法)。
内容的提问来源于stack exchange,提问作者Betjamin Richards
相关产品推荐
相关产品推荐

