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”
您的问题在于它不适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)
还要检查模型端验证。这也可能会导致问题。
| 归档时间: |
|
| 查看次数: |
4695 次 |
| 最近记录: |