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函数时,将在保存配置文件时对其进行检查。
我遇到了同样的问题,我试图检查在更新模型时是否创建或删除了新的关系。
我尝试使用
在寻找解决方案时,我找到了这篇简短的文章来解决我们的问题:link
使用
将此与
我知道您正在寻求实现基于文本的更改日志,但是我建议您通过
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.
我没有使用
要创建文本文件日志以及此数据库纸张记录,可以在