是否在 HABTM 关系的联接表中调用 ActiveRecord 回调?
在测试 acts_as_audited 时,我发现(也如此处) :with_associations 标志不会生成 HABTM 关系的审计表条目。
例如:(
User < ActiveRecord::Base
has_and_belongs_to_many: :groups
acts_as_audited, with_associations: groups
Group < ActiveRecord::Base
has_and_belongs_to_many: :users
acts_as_audited, with_associations: users
以及经过测试的变体,即带/不带 with_associations)
在源代码中,我们可以看到,acts_as_audited 所做的所有事情都是向审核表添加像 before_update 和 after_create 这样的回调。显然这些没有添加到连接表中。
我尝试制作如下模型:
GroupsUsers < ActiveRecord::Base
acts_as_audited
after_save: :test
def test
logger.debug "test"
end
但没有看到针对用户或组的 CRUD 操作的审计表添加任何内容。我可以在日志中看到作用于连接表的 SQL 语句,因此这表明连接表在内部进行了更改,从而绕过了正常的回调。
这是真的吗?对于让acts_as_audited 注意连接表或记录HABTM 关联有什么建议吗?
While testing acts_as_audited, I discovered (as also described here) that the :with_associations flag does not produce audit table entries for HABTM relationships.
For example:
User < ActiveRecord::Base
has_and_belongs_to_many: :groups
acts_as_audited, with_associations: groups
Group < ActiveRecord::Base
has_and_belongs_to_many: :users
acts_as_audited, with_associations: users
(and tested variations, ie. with/without with_associations)
In the source, one can see that all acts_as_audited does is adds callbacks like before_update and after_create to the audited tables. Apparently these are not added to the join tables.
I tried making a model like:
GroupsUsers < ActiveRecord::Base
acts_as_audited
after_save: :test
def test
logger.debug "test"
end
but did not see any additions to the audit table for CRUD operations on Users or Groups. I can see the SQL statement acting on the join table in the logs so this suggests that the join table is altered internally in such a way that the normal callbacks are bypassed.
Is this true? Any suggestions for getting acts_as_audited to notice the join table or to log HABTM associations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关联回调
has_and_belongs_to_many
与挂钩到 Active Record 对象生命周期的普通回调类似,您还可以定义在将对象添加到关联集合或从关联集合中删除对象时触发的回调。
可以通过将回调作为数组传递来堆叠它们。示例:
可能的回调有:
before_add
、after_add
、before_remove
和after_remove
。如果任何
before_add
回调抛出异常,则该对象将不会添加到集合中。同样,如果任何
before_remove
回调抛出异常,该对象将不会从集合中删除。Association callbacks
has_and_belongs_to_many
Similar to the normal callbacks that hook into the life cycle of an Active Record object, you can also define callbacks that get triggered when you add an object to or remove an object from an association collection.
It's possible to stack callbacks by passing them as an array. Example:
Possible callbacks are:
before_add
,after_add
,before_remove
andafter_remove
.If any of the
before_add
callbacks throw an exception, the object will not be added to the collection.Similarly, if any of the
before_remove
callbacks throw an exception, the object will not be removed from the collection.