检测rails has_many:through关系中的更改

Detecting changes in a rails has_many :through relationship

我有一个具有多个has_many和has_many的模型:通过模型关系。例如,在我的User类中,我有:

has_many:languages,通过::profile_languages

我想要的是能够使用\\'User.changes \\'函数检测何时添加或删除这些属性,该函数返回一个数组,该数组由User.language_ids =函数调用时已更改。

有没有其他人尝试过这样做或有经验吗?

有关ActiveModel更改功能的信息:http://api.rubyonrails.org/classes/ActiveModel/Dirty.html

编辑:根据要求,这是我在做什么。

在分配了用户的属性之后,在保存属性之前,我正在查看从.changes返回的所有值,以便将所有更改记录在外部日志中。

因此,如果我叫u.name = "新名称"

然后u.changes返回{名称:[\\'旧名称\\',\\'新名称\\']}

但是,当我向用户传递一堆语言ID时,例如

u.language_ids = [4,5]

然后创建了许多ProfileLanguage模型,并且u.changes哈希保留为空白。

我正在尝试在ProfileLanguage模型中创建一些回调,这些回调将手动创建某种哈希,但是我想知道这是否确实是最佳解决方案。


我现在要解决的问题是将回调添加到has_many函数中:

1
2
3
has_many :languages, through: :profile_languages,
        :after_add => :language_add,
        :before_remove => :language_remove

并将此信息添加到自定义哈希中,当我查看.changes函数时,将在保存配置文件时对其进行检查。


我遇到了同样的问题,我试图检查在更新模型时是否创建或删除了新的关系。

我尝试使用model.relationship.any? { |a| a.changed? },但这只能检测已存在的现有对象的更改,因此它不适用于创建和删除关系。

在寻找解决方案时,我找到了这篇简短的文章来解决我们的问题:link

使用model.select { |a| a.new_record? || e.marked_for_destruction? }.any?我已经能够获取所有正在创建或销毁的记录。

将此与a.changed?结合在一起,我可以得到我的人际关系中的所有变化。


我知道您正在寻求实现基于文本的更改日志,但是我建议您通过paper_trail gem来研究完整的对象版本控制,以此作为实现所需目标的一种方法。它根据其自述文件提供此功能:

PaperTrail can restore three types of associations: Has-One, Has-Many, and Has-Many-Through. In order to do this, you will need to create a version_associations table, either at installation time with the rails generate paper_trail:install --with-associations option or manually. PaperTrail will store in that table additional information to correlate versions of the association and versions of the model when the associated record is changed.

我没有使用paper_trail的has-man-through功能,??但是我将它用于没有关联的对象,并发现它非常好并且易??于实现。

要创建文本文件日志以及此数据库纸张记录,可以在after_save回调中使用paper_trail的diff功能。