Rails 5.2 Association callbacks not firing on before_add or before_remove

一世执手 提交于 2019-12-25 00:35:45

问题


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?

As far as I can see, it is not the issue described in this question either.


回答1:


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"

eg:

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

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

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"

eg:

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


来源:https://stackoverflow.com/questions/56951926/rails-5-2-association-callbacks-not-firing-on-before-add-or-before-remove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!