简体   繁体   中英

Ember + Handlebars render Rails validation errors as [object Object]

Given this json response:

{"username":null,"errors":{"password":["is required"],"username":["is required","is too short","is invalid"],"email":["is required","is invalid"]}}

I want to render the first error message of each attribute. Ember picks up the errors correctly, and I am able to parse them in an Handlebars template, like:

<div {{bind-attr class='errors.email:error'}}>
  <label>Email Address</label>
  {{view Ember.TextField type='email' valueBinding='model.email' placeholder='Email Address'}}
  <small class='below'>{{errors.email}}</small>
</div>

But {{errors.email}} renders [object Object] or a multitude of these. Adding .[0] , or firstObject reduces this to only render [object Object] once, but it is not parsing the correct error message.

Edo, this looks like it's working properly.

http://emberjs.jsbin.com/OZaNAYuc/1/edit

When using the ActiveModelAdapter, error messages get automatically paired to attribute / message. As @kingpin2k explained in his gist, errors.email.firstObject will get the first object, from which you'll need the message attribute.

I created this helper, to dry it up a bit:

Ember.Handlebars.helper('error', function(context) {
    if(context && context.length)
        return context[0].message;
});

Use it like this in your hbs templates:

{{error errors.email}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM