Rails 5.2 Association callbacks not firing on befo

2019-08-29 03:14发布

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条回答
仙女界的扛把子
2楼-- · 2019-08-29 03:48

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
查看更多
登录 后发表回答