Can I add a `after_add` callback to a ruby association in a model decorator?


The association is has_and_belongs_to_many and is defined in a gem. I need to know when a new one is added so from what I can tell the answer is the after_add callback, but I can't figure out how to add this after the fact.

Code I have now that doesn't work:

(In gem)


module Spree
  class Job < Spree::Base
    has_and_belongs_to_many :users, join_table: 'spree_jobs_users', class_name: Spree.user_class.to_s

(My broken code)


Spree::Job.class_eval do
  has_and_belongs_to_many :users, join_table: 'spree_jobs_users', 
class_name: Spree.user_class.to_s, after_add: :test

  def test
   # after method

Is there any way for this to work? Or any other way for me to find out when a new job is added?

Show source
| ruby   | ruby-on-rails   | spree   | spree-auth-devise   2017-05-11 23:05 1 Answers

Answers ( 1 )

  1. 2017-05-12 05:05

    If you want some code to run every time you add a row to the spree_jobs_users table, it seems to me that code should be the responsibility of the join table, not Spree::Job. I would recast this as a has_many :through relationship, create a model for your join table, and put your code in an :after_create hook on that model.

    Per the Rails docs, "The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity."

◀ Go back