I have two ActiveRecord models having a HABTM relationship with eachother. When I add an AccessUnit through a form that allows zones to be added by checking checkboxes I get an exception that the AccessUnitUpdaterJob can't be enqueued because the access unit passed can't be serialized (due to the fact that the identifier is missing). When manually calling save on the primary object, the issue is resolved but of course this is a workaround and not a proper fix.
TLDR; it seems the after_add callback is triggered before the main object is saved. I'm actually unsure if this is a bug in Rails or expected behavior. I'm using Rails 5.
The exact error I encounter is:
ActiveJob::SerializationError in AccessUnitsController#create
Unable to serialize AccessUnit without an id. (Maybe you forgot to call save?)
Here's some code so you can see the context of the issue:
class AccessUnit < ApplicationRecord
has_and_belongs_to_many :zones, after_add: :schedule_access_unit_update_after_zone_added_or_removed, after_remove: :schedule_access_unit_update_after_zone_added_or_removed
def schedule_access_unit_update_after_zone_added_or_removed(zone)
# self.save adding this line solves it but isn't a proper solution
puts "Access unit #{name} added or removed to zone #{zone.name}"
# error is thrown on this line
AccessUnitUpdaterJob.perform_later self
end
end
class Zone < ApplicationRecord
has_and_belongs_to_many :access_units
end