Expected format for validation errors in Ember Data (using ActiveModel::Serializers)

≯℡__Kan透↙ 提交于 2020-01-16 19:14:29

问题


Unfortunately, ActiveModel::Serializers does not currently support validation errors, though they're scheduled for 1.0. Until then, I've got to hack a solution of my own. The big problem? I have no idea what format Ember Data's ActiveModelAdapter expects these errors to be in. I tried simply passing in the errors property, but Ember Data didn't pick up on it:

class MySerializer < ActiveModel::Serializer
  attributes :errors
end

So what should I pass in instead?


回答1:


I use this method to render validation errors (note that you don't use the serializer at all):

def render_validation_errors errors
  render json: {errors: errors.to_h}, status: 422
end

You would use it like this:

def create
  model = Model.new model_params
  if model.save
    respond_with model
  else
    render_validation_errors model.errors
  end
end

The format expected by ActiveModelAdapter is:

{"errors":{"title":"should begin with a capital letter"}}


来源:https://stackoverflow.com/questions/22971555/expected-format-for-validation-errors-in-ember-data-using-activemodelserializ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!