1

save为了处理边缘情况,我重写了 ActiveRecord 模型:

class A < ActiveRecord::Base
  belongs_to :b

  def save *args
    super
  rescue ActiveRecord::StatementInvalid => ex
    log_warning
    retry unless @foo
    throw ex
  end
end

a = A.new
a.build_b
a.save

而且我发现当save函数第二次执行时(因为retry),我得到一个与关联记录有关的 MySQL 错误b

ActiveRecord::StatementInvalid: Mysql2::Error: 字段 'created_at' 没有默认值:INSERT INTO bsVALUES ()

使用断点我可以看到在 之后, (参见源代码retry的调用对于要保存的属性有一个空数组( ),而它是在第一次调用时。ActiveRecord#_create_recordb[]["full_name","company","id","owner_id","created_at","updated_at"]

为什么会retry破坏关联记录的自动保存?我能做些什么呢?

上面的链接适用于 ActiveRecord 4.2.11.3,这是我正在从事的项目的版本。

4

1 回答 1

1

如果我是你,我不会覆盖 save 方法。我宁愿使用around_save回调。

class A < ActiveRecord::Base
  around_save :saving_retry

  def saving_retry
    yield
  rescue ActiveRecord::StatementInvalid => ex
    log_warning
    save unless @foo
  end
end
于 2021-07-11T00:05:53.340 回答