render( json: UserSerializer.response_error(current_user.errors.messages).to_json)
user_serializer.rb
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :email
def self.response_error(error)
error
end
end
它给出了如下响应:
[
"Password can't be blank"
]
但我需要展示
"Password can't be blank"
我试图使用“full_messages”,但结果是一样的
def self.response_error(error)
error.join(', ')
end
你可以这样做。问题是它需要是一个数组。因为可能存在多个错误。
[
"Email can't be blank",
"Password can't be blank"
]
这将是以上代码的结果:
"Email can't be blank, Password can't be blank"
通常,无论一个或多个错误,数组都更容易在前端使用。
当你完全确定只有这一个错误时,你也可以做error.join('')
来获取字符串。