1

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)

job.rb

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

(My broken code)

job_decorator.rb

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
  end
end

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

1 Answers1

0

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."

http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

jmschles
  • 274
  • 1
  • 6