Rails Rails 6.1 的 ActiveModel#errors 翻新

lulalala · 2020年06月29日 · 最后由 piecehealth 回复于 2020年07月01日 · 2581 次阅读

之前在这有发过两篇文(1, 2),关于想改善 ActiveModel#errors。后来 Rails 团队终于把改变给加进去 master 了,预计今年会以 Rails 6.1 的方式推出。在此想先介绍本次改变有什么 deprecation 跟 breaking changes。也希望在 6.1rc1 推出前,搜集一下大家的意见看看如何改进~

https://code.lulalala.com/2020/0619-1013.html

原来前后经历了三年。

ksec 回复

哈哈岁月不饶人,感谢你不时还转贴关于这个的新闻^^

嗯 一直在做的内容 特别是前后端分离的时候 非常的不想要 prefix attribute name. 如果是自定义验证方法 通过errors.add() 方法添加错误信息 其实是可以包装错误 采用 I18n 的方式输出我们想要的错误信息的

# 例如
erros.details  #=> {:customer=>[{:error=>:blank}], :identification_type=>[{:error=>:blank}]}

errors.add(:identification_type, :custom_error, message: "Custom Error")   # => ["can't be blank", "Custom Error"] 

# 再次输出
errors.details #=> {:customer=>[{:error=>:blank}], :identification_type=>[{:error=>:blank}, {:error=>:custom_error}]} 
errors.messages # => {:customer=>["must exist"], :identification_type=>["can't be blank", "Custom Error"]}

我的想法是采用 I18n 的方式包装输出 需要的错误信息

需要 登录 后方可回复, 如果你还没有账号请 注册新账号