【发布时间】:2016-11-17 21:08:20
【问题描述】:
我有两个具有 HABTM 关系的 ActiveRecord 模型。 当我通过允许通过选中复选框添加区域的表单添加 AccessUnit 时,我得到一个异常,即 AccessUnitUpdaterJob 无法入队,因为传递的访问单元无法序列化(由于缺少标识符) .在主对象上手动调用 save 时,问题已解决,但当然这是一种解决方法,而不是正确的修复方法。
TLDR;似乎在保存主对象之前触发了 after_add 回调。我实际上不确定这是 Rails 中的错误还是预期的行为。我正在使用 Rails 5。
我遇到的确切错误是:
ActiveJob::SerializationError in AccessUnitsController#create
Unable to serialize AccessUnit without an id. (Maybe you forgot to call save?)
这里有一些代码,您可以查看问题的上下文:
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
【问题讨论】:
-
至少看起来api.rubyonrails.org/classes/ActiveRecord/Associations/… 应该在“关联扩展”部分指定是否在保存之前触发 after_add。
标签: ruby-on-rails rails-activerecord ruby-on-rails-5 has-and-belongs-to-many