无法在 after_create 回调上更新新记录

Pet*_*r R 3 ruby-on-rails

class Model < ActiveRecord::Base
  after_create :set_slug

  def set_slug
    update_column(:slug, to_slug)
  end

  def to_slug
    #code to create slug
  end
end
Run Code Online (Sandbox Code Playgroud)

如果回调是 after_create,为什么会返回“ActiveRecord::ActiveRecordError: 无法更新新记录”?问题出在“update_column”

sk1*_*712 7

您的问题在于它不适update_columns用于新记录。为什么不使用 update_attributes` 来代替

  after_create do
    self.update_attributes(slug: to_slug)
  end
Run Code Online (Sandbox Code Playgroud)

如果您愿意,您也可以尝试以下方法

if new_record?
  return
else
 update_column(:slug, to_slug)
end
Run Code Online (Sandbox Code Playgroud)

还要检查模型端验证。这也可能会导致问题。

  • 我不明白为什么这会被投票通过。问题很明显,这是一个“after_create”回调,因此记录应该已经被持久化了。 (2认同)