gpt4 book ai didi

ruby-on-rails-4 - 使用 papertrail 时恢复关联内的关联

转载 作者:行者123 更新时间:2023-12-01 06:49:48 24 4
gpt4 key购买 nike

在 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 恢复删除的pointlog

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

最佳答案

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

关于ruby-on-rails-4 - 使用 papertrail 时恢复关联内的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29283808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com