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?
If you want some code to run every time you add a row to the
spree_jobs_userstable, it seems to me that code should be the responsibility of the join table, notSpree::Job. I would recast this as ahas_many :throughrelationship, create a model for your join table, and put your code in an:after_createhook on that model.Per the Rails docs, "The simplest rule of thumb is that you should set up a
has_many :throughrelationship 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