轨道 - 解析嵌套表单关联错误



我正在尝试使用以下格式的索引键对象显示关联错误:

:errors=>{
:questions=>{
0=>{:title=>"can't be blank"},
1=>{:title=>"can't be blank"}
}
}

Rails 5 提供了一种显示错误索引的方法,但使用的格式如下:

questions[0].title, 
questions[1].title

我的解决方案有点讨厌,是像这样解析错误响应

def parse_errors
{
errors: {
questions: @post.questions.enum_for(:each_with_index).collect { |question, index|
{
index => question.errors.messages
} unless question.valid?
}.inject({}, :merge).transform_values {|v| v.transform_values &:first }
}.merge!(@post.errors.messages)
}
end

我得到

{
:errors=>{
:questions=>{
0=>{
:title=>"can't be blank"
},
1=>{
:title=>"can't be blank"
}
}, 
:"questions.title"=>["can't be blank"], 
:title=>["can't be blank"]
}
}

但我希望以下结果省略默认的问题错误消息:"questions.title"=>["不能为空"], 喜欢这个:

{
:errors=>{
:questions=>{
0=>{
:title=>"can't be blank"
},
1=>{
:title=>"can't be blank"
}
},  
:title=>["can't be blank"]
}
}

那么,有没有办法清理此代码以显示具有预期格式的帖子和问题的错误?

谢谢。

解析嵌套表单关联错误

不确定,但您可以通过以下方式删除默认错误消息:

  1. 使用self.errors.clear清除所有错误。
  2. 使用self.errors.add将所有错误消息放回正确/所需的位置。

最新更新