本文介绍了Rails 5.2关联回调未在before_add或before_remove上触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有HABTM的活动模型:

I have an Activity model with HABTM:

has_and_belongs_to_many :contacts,
                        -> { distinct },
                        before_add: :contact_calculate_score,
                        before_remove: :contact_calculate_score


def contact_calculate_score(contact)
  binding.pry
  contact.calculate_score
end

对此有很多问题,例如这一个.

There are quite a few questions on this, for example this one.

我尝试使用'<<'将活动插入联系人中,但仍然不会触发回调.为什么不叫它?

I have tried using '<<' to insert activities into contacts, but still the callback does not fire. Why is it not being called?

据我所知,这不是.

推荐答案

所以代码正确,问题是我的期望与我在控制台中所做的不匹配,这是这​​样的:

So the code is correct, the issue was my expectation did not match what I was doing in the console, which was this:

"a contact_instance".activities << "an activity instance"

例如:

   Contact.first.activities << Activity.create(...)

我必须在Contact模型中定义回调才能起作用.

I would have to define the callbacks in the Contact model for that to work.

或者,要触发回调,我必须将Contact实例推入Activity的联系人中:

Alternatively, to get my callbacks to fire, I have to push a Contact instance into the contacts for an Activity:

"an activity instance".contacts << "a contact_instance"

例如:

Activity.first.contacts << Contact.create(...) or Contact.find(...) etc

这篇关于Rails 5.2关联回调未在before_add或before_remove上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!