本文介绍了检测rails has_many:through关系中的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a model that has a number of has_many, and has_many :through model relationships. For example, in my User class I have:

has_many:languages,通过::profile_languages

has_many :languages, through: :profile_languages

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

What I would like is to be able to detect when these are added or removed using the 'User.changes' function, which returns an array of attributes that have been changed when called with the User.language_ids= function.

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

Has anyone else tried to do this, or have experience with this?

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

Info on the ActiveModel changes function: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html

根据要求,这是我在做什么.

As requested, here is what I am doing.

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

After a user's attributes are assigned and before it is saved, I am looking at all of the values returned from the .changes, in order to log all the changes made in an external log.

所以,如果我叫u.name ="new name"

So if I call u.name = "new name"

然后u.changes返回{name:['old name','new name']}

then u.changes returns {name: ['old name', 'new name']}

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

However, when I pass a user a bunch of language ids, such as

u.language_ids = [4,5]

u.language_ids = [4,5]

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

Then there are a number of ProfileLanguage models created, and the u.changes hash is left blank.

我试图在ProfileLanguage模型中创建一些回调,这些回调将手动创建某种哈希,但是我想知道这是否真的是最好的解决方案.

I am attempting to create some callbacks in the ProfileLanguage model that would manually create some sort of a hash, but I am wondering if this is indeed the best solution.

推荐答案

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

My somewhat dirty solution I am going with now is to add callbacks to the has_many function:

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

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

And adding this info to a custom hash that will be checked on the saving of a profile when I am looking at the .changes function.

这篇关于检测rails has_many:through关系中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 22:08