Rails + Validation Errors


#1

Edit: The correct answer is below, you need to iterate over the error objects. I’ve created a JSBin: http://jsbin.com/motuvaye/6/edit

I’m trying to handle server side validation errors with vanilla ember.

My Rails controller:

def create
  @story = Story.create(story)
  if @story.valid?
    render json: @story
  else
    render json: {errors: @story.errors}, status: 422
  end
end

My route:

MyApp.StoriesNewRoute = Ember.Route.extend({
  model: function() {
  return this.store.createRecord('story');
},
actions: {
  create: function(story){
    var route = this;
    story.save().then(function(){
      route.transitionTo('stories');
    });
  }
 }});

The errors that come back currently look like this:

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

What should the errors look like?

How can I insert the title error onto my handlebars page so that I can show the title error next to the title ( not in a general isError block )

Thank you!


#2

I was just about to ask a similar question. I’ve got the question on StackOverflow, too, though it hasn’t been answered after several days. Quite simply, what format is EmberData expecting its errors to be in? I can’t find this documented anywhere.


#3

@droberts @timothythehuman it should be something like

{{#each errors.fieldname}}
  {{this.message}}
{{/each}}

#4

I answered on Stack Overflow. Note that there are some other issues with errors at the moment, please have a look at the following post and add your comments if you have any:

Alex


#5

@xeppelin Do you have to manually set errors, or is Ember suppose to handle that for you? Because nothing is rendered when I try:

{{#each errors.fieldname}}
  {{this.message}}
{{/each}}

(Replacing fieldname with the appropriate field.)


#6

Thanks to everyone who answered. The correct answer is that you need to iterate over the error messages, as described above.

I’ve created a JSBin that I keep updating that highlights the solution here, as well as some other issues I’m wrestling with. I’ll update the original post with the JSBin and post the other questions separately.


#7

I have just filed a pull request to allow record.save() even when the record is invalid. Please have a look and review if this affects you! Thanks.


#8

Thanks, I think this will go a long way towards solving the problem.