3

在 paper_trail 中的一个警告是只恢复了第一级关联,如果您在关联中有关联,这是一个问题

如果我有...

class Student < ActiveRecord::Base
  has_paper_trail
  has_many :attendances, dependent: :destroy
end

class Attendances < ActiveRecord::Base
  has_paper_trail
  has_many :point_logs, dependent: :destroy
end

class PointLogs < ActiveRecord::Base
  has_paper_trail
end

如果我删除了一个学生,我将student.versions.last.reify(:has_many => true)恢复已删除的出勤率和学生,然后分别pointlog.version.last.reify恢复已删除的点日志

这是恢复嵌套级联删除的最佳方法,还是有更好的方法来解决 paper_trail 中的这个警告?

4

1 回答 1

0

因此,这是一个可能的解决方案,它可以更进一步。我有一个类似的问题,但希望它不要那么明确,因为它必须适用于多个模型。这是我创建的一个模块,我将其包含在版本链的顶层中,因此在您的情况下,我会将其包含在 Student 中。

  # This method finds the current reified model's has_many relationships and
  # recursively reifies has_many relationships until the end
  #
  # @param [ActiveRecord::Base] model_version is a reified active_record model
  # @return [ActiveRecord::Base] model_version
  def self.reify_has_many_associations(model_version)
    associations = model_version.class.reflect_on_all_associations(:has_many).select { |a| a.klass.paper_trail.enabled? }.map(&:name)
    if associations.present?
      associations.each do |a|
        models = model_version.method(a).call
        models.each do |m|
          if m.version
            m.version.reify(has_many: true)
            ::Revertable.reify_has_many_associations(m)
          end
        end
      end
    end
    model_version
  end
于 2017-03-17T12:48:57.250 回答