Ember: error.messages does not show server errors on save

假装没事ソ 提交于 2020-01-02 07:27:28

问题


When trying to create a new record, the errors.messages do not render as described in the docs. That said, the console does render the error Error: The backend rejected the commit because it was invalid: {email: has already been taken}.

I have the following in my ember-cli app:

Router

Router.map ->
  this.route 'users/new', path: '/signup'

Route

UsersNewRoute = Ember.Route.extend(
  model: ->
    return @store.createRecord('user')
)

Controller

UsersNewController = Ember.ObjectController.extend(
  actions:
    save: ->
      @get('model').save()
)

Template

<h2>Sign up!</h2>
<form {{action 'save' on='submit'}}>
  <label for="email">Email</label>
  {{input id='email' type='email' placeholder='Enter Login' value=email}}
  <label for="password">Password</label>
  {{input id='password' placeholder='Enter Password' type='password' value=password}}
  <button type="submit">Sign Up</button>
</form>

{{#each errors.messages}}
  <p>{{message}}</p>
{{/each}}

On the server, I'm using AMS with the following Controller:

class UsersController < ApplicationController

  def index
    @users = User.all
    render json: @users
  end

  def show
    @user = User.find(params[:id])
    render json: @user
  end

  def create
    user = User.new(permitted_params(params[:user]))

    if user.save
      render json: user
    else
      render_validation_errors user.errors
    end
  end

  private

  def permitted_params(params)
    params.permit(:email, :password)
  end

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

end

What am I doing wrong?


回答1:


The Ember Data docs are out of date, they are busy trying to finish up 1.0. You must be using the ActiveModelAdapter (not the RESTAdapter):

App.ApplicationAdapter = DS.ActiveModelAdapter; 

And the json returned should be like this

 {
    errors:
    {
       foo:'The world is ending!',
       bar:'Error Error Error'
    }
 }

And preferably you should wrap your each statement with an if

{{#if errors}}
  {{#each errors.messages}}

  {{/each}}
{{/if}}

Here's an example, click save with fields blank:

http://jsbin.com/motuvaye/24/edit

Additionally you can extend the rest adapter and add the functionality there, I talked about it here: Ember Data model's errors property (DS.Errors) not populating



来源:https://stackoverflow.com/questions/23975722/ember-error-messages-does-not-show-server-errors-on-save

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