gpt4 book ai didi

ruby-on-rails - 无法在 after_create 回调上更新新记录

转载 作者:行者123 更新时间:2023-12-04 05:46:36 26 4
gpt4 key购买 nike

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

如果回调是 after_create,为什么会返回 'ActiveRecord::ActiveRecordError: cannot update a new record'?问题在于“update_column”

最佳答案

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

  after_create do
self.update_attributes(slug: to_slug)
end

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

if new_record?
return
else
update_column(:slug, to_slug)
end

还要检查模型方面的验证。这也可能导致问题。

关于ruby-on-rails - 无法在 after_create 回调上更新新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30701854/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com