3

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?

Josh Smith
  • 14,674
  • 18
  • 72
  • 118

1 Answers1

2

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

Community
  • 1
  • 1
Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
  • 1
    I am using the `ActiveModelAdapter`. I get JSON returned that reads: `{ "errors": { "email": "can't be blank", "password": "can't be blank" } }`. Something else must be awry here. – Josh Smith Jun 01 '14 at 03:53
  • I also tried, per your example, moving the `save` action into the `UsersNewRoute`, passing in `user` to the function, but to no avail. – Josh Smith Jun 01 '14 at 03:59
  • 1
    Ah, not doing `.then()` and working with the promises was the last thing that did it for me. – Josh Smith Jun 01 '14 at 04:05