【发布时间】:2021-08-06 05:03:19
【问题描述】:
这是一个简单的控制器更新操作:
def update
note = Note.find(params[:id])
if note.update(note_params)
render json: note.to_json
else
render json: {errors: note.errors}, status: :unprocessable_entity
end
end
这会在表单中呈现错误
{"errors":{"title":["can't be blank"]}}
但我想要它的形式
{"errors":{"title":["Title can't be blank"]}}
只需使用 {errors: note.errors.full_messages}
给
{:errors=>["Title can't be blank"]} 并错过了属性键。
我可以把它变成所需形式的唯一方法似乎有点复杂:
full_messages_with_keys = note.errors.keys.inject({}) do |hash, key|
hash[key] = note.errors.full_messages_for(key)
hash
end
render json: {errors: full_messages_with_keys}, status: :unprocessable_entity
这可行,但我必须这样做似乎很奇怪,因为它似乎是在 SPA 前端进行验证的一个非常常见的用例。是否有内置方法/更规范的方式?
【问题讨论】:
-
ActiveModel::Errors上仅有的两个用于获取消息中的人性化/翻译属性名称的内置选项是full_messages和full_messages_for。像你一样使用inject滚动你自己就是我会做的事情。
标签: ruby-on-rails validation activerecord