提问人:Backo 提问时间:4/13/2023 最后编辑:Backo 更新时间:4/13/2023 访问量:303
errors.add(:base, 'foo') 不会在 Rails 7 中止保存
errors.add(:base, 'foo') does not abort save in Rails 7
问:
在回答这个问题之后,我确认在 Rails 7 中(与 Rails 6 不同)仅有效地向模型对象添加错误。根据官方文件[第7.5章]:errors.add(:base, 'foo')
errors.add(:base, :invalid, 'foo')
当您想说对象无效时,您可以向 :base 添加错误,无论其属性的值如何。
我一直使用这个事实来中止将对象保存到数据库和回调中,并且它一直有效,直到 Rails 7。before_create
before_save
事实上,在 Rails 7 中,一个调用 save 例如 即使记录已添加到记录中,也要保存记录,根据旧版本的 Rails 的行为和文档的常识,这不应该发生。@resource.save
errors[:base]
我还注意到,如果您添加回调,但既不添加也不添加 .errors[:base]
before_validation
before_create
before_save
有没有机会通过在其他回调中添加模型对象来使模型对象真正无效(即使其不被保存),而不是 ?或者,新的 Rails 7 方法是否改变了用于此类问题?或者,这是一个错误吗?errors[:base]
before_validation
before_validation
答:
1赞
anothermh
4/13/2023
#1
您需要使用 ,例如:throw :abort
before_destroy do
errors.add(:base, 'records cannot be destroyed')
throw :abort
end
活动记录回调文档中的停止执行中对此进行了介绍。
评论
validates ...
validate ...
before_validation
before_create
before_save