0
votes

I know there's the after_add and after_remove association callbacks you can use when defining the association in rails as described under the Assocation Callbacks section here - http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

But the gem i'm using already defined the association like so:

has_many :payments, as: :source

I tried going with class_eval or ActiveSupport::Concern to override the association so it would look like this:

has_many :payments, as: :source, after_add: :payment_added, after_remove: :payment_removed

But it isn't working for me (if you think it should let me know)

So rather than trying to override it i'm wondering if there's any other way to observe something similar to after_remove and after_add, basically when a payment has been added or removed.

1

1 Answers

0
votes

Callbacks don't have to be defined on the association definition line. They can be added at any time to the associated object - especially if they are only added to this associated object.

Here's a link to the docs on callbacks here

To replace your after_add callback what you want is an after_create callback. and your after_remove you could use after_destroy

eg:

has_many :payments, as: :source

and in payments:

after_create :payment_added
after_destroy :payment_removed

Now - you've moved it into the child object, you may need to adjust the logic to call a method on the parent object... also, if these payments can be added to something other than the main object it might not work, but it's an option.