Paper Trail:每当关联模型更改时,在父级上创建一个版本? [英] Paper Trail: create a version on parent whenever associated model changes?

查看:90
本文介绍了Paper Trail:每当关联模型更改时,在父级上创建一个版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rails应用程序,需要在记录上显示审核跟踪,该记录具有很多数据.我的Record和相关的Datum模型上有paper_trail,它可以很好地保存它们的版本.

I'm working on a Rails app where I need to show the audit trail on a Record, which has_many Data. I have paper_trail on my Record, and associated Datum models, and it is saving versions of them just fine.

但是,我需要的是一个版本的记录,只要一个或多个关联数据发生更改,就可以创建该版本.当前,它在每个要更改的基准上创建版本,但是仅当记录的属性更改时,才创建记录的版本.当关联的数据发生更改时,它就不会执行此操作.

However, what I need is for one version for Record to be created whenever one or more associated Data are changed. Currently, it creates versions on each Datum that changes, but it only creates a version of the Record if the Record's attributes change; it's not doing it when the associated Data change.

我尝试将touch_with_version放入Record的after_touch回调中,就像这样:

I tried putting touch_with_version in Record's after_touch callback, like so:

class Record < ActiveRecord::Base
  has_many :data

  has_paper_trail

  after_touch do |record|
    puts 'touched record'
    record.touch_with_version
  end

end

class Datum < ActiveRecord::Base
  belongs_to :record, :touch => true

  has_paper_trail

end

触发after_touch回调,但是不幸的是,它为每个Datum创建了一个新版本,因此,在创建Record时,它已经具有10个版本,每个Datum都有一个版本.

The after_touch callback fires, but unfortunately it creates a new version for each Datum, so when a Record is created it already has like 10 versions, one for each Datum.

有没有办法在回调中告诉您是否已创建一个版本,所以我不创建多个版本?就像签入一个Record回调一样,如果Datum已经触发了一个版本,就不做任何其他事情了吗?

Is there a way to tell in the callbacks if a version has been created, so I don't create multiples? Like check in one of the Record callbacks and if Datum has already triggered a version, don't do any more?

谢谢!

推荐答案

这对我有用.

class Place < ActiveRecord::Base
  has_paper_trail
  before_update :check_update

  def check_update
    return if changed_notably?

    tracking_has_many_associations = [ ... ]
    tracking_has_has_one_associations = [ ... ]

    tracking_has_many_associations.each do |a|
      send(a).each do |r|
        if r.send(:changed_notably?) || r.marked_for_destruction?
          self.touch
          return
        end
      end
    end
    tracking_has_one_associations.each do |a|
      r = send(a)
      if r.send(:changed_notably?) || r.marked_for_destruction?
        self.touch
        return
      end
    end
  end
end

这篇关于Paper Trail:每当关联模型更改时,在父级上创建一个版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆