Rails模型为create与update/touch场景分别配置has_paper_trail条件的问题
问题根因
多次调用has_paper_trail会覆盖之前的类配置,不会叠加多个场景的监听规则,这是原代码无法生效的核心原因。
正确实现
PaperTrail v4.0.0及以上版本支持:if参数的Proc接收两个入参,分别为当前模型实例、本次触发的事件类型(:create/:update/:touch),可以直接合并不同场景的判断逻辑:
class MyModel < ActiveRecord::Base has_paper_trail( if: Proc.new { |mymodel, event| case event when :create mymodel.whodunnit.present? when :update, :touch mymodel.status.present? else false end }, on: [:create, :update, :touch] ) before_create do PaperTrail.request.whodunnit = whodunnit if whodunnit.present? end attr_accessor :whodunnit end
低版本兼容方案
如果使用的PaperTrail版本低于4.0,不支持双参数Proc,可以通过模型本身的状态判断场景:
has_paper_trail( if: Proc.new { |mymodel| # 新建记录对应create场景,已存在记录对应update/touch场景 mymodel.new_record? ? mymodel.whodunnit.present? : mymodel.status.present? }, on: [:create, :update, :touch] )
内容的提问来源于stack exchange,提问作者Júlio Falbo
相关产品推荐
相关产品推荐

