YHDEV
YHDEV

Reputation: 477

Ember.js: Check if a record already exists in model ( Error - the adapter's response did not have any data)

What I'm trying to do: User will get error if user trying to register with username or email that are already registered in model.

When I tried to register with username(id) that is not registered, I got this error: Error: Assertion Failed: You made a request for a user with id kevin, but the adapter's response did not have any data I'm debugging with console and reading documentation but I'm not sure why I get this error, please help me.

in the controller app/auth/register.js

var AuthRegisterController = Ember.ObjectController.extend({
  name:     null,
  username: null,
  email:    null,
  password: null,
  error:    null,

  actions: {
    register: function(){
      this.set('error', null);
      var userInfo = this.getProperties('name', 'username', 'email', 'password');

      ...

      if(this.store.find('user', userInfo.username)){
        return this.set('error', 'The username is already registered.');
      }
      if(this.store.find('user', {email: userInfo.email})){
        return this.set('error', 'The email is already registered.');
      }

      ...

    }
  }

});

export default AuthRegisterController;

User model structure : app/models/user.js

var User = DS.Model.extend({
  name: DS.attr('string'),
  email: DS.attr('string'),
  password: DS.attr('string'),
  posts: DS.hasMany('post'),
});

User.reopenClass({
  FIXTURES: [{
    id: 'will',
    name: 'Will Smith',
    email: '[email protected]',
    password: 'password'
  }]
});

export default User;

Ember documentation - Finding Records

Upvotes: 0

Views: 2123

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

find is an asynchronous method, it will always return a promise immediately (aka all of those if statements will execute). Using Ember Data for finding out if a record exists or not is overkill, and doesn't make sense. It's a major flaw to return user information for a different user when they type in the username/email that's already in the system. That's what Ember Data is used for, record management, not does this record exist.

All that being said, just create an endpoint on your server /available_user that allows you to post the username/email and it sends back a 200 with a results such as {result:'ok'} or {result:'duplicate email'} etc.

var store = this.store;
...
var request = $.ajax({
    url:'/available_user',
    type:'POST',
    data: getProperties
});

request.then(function(results){
  if(results.ok){
    record = store.createRecord('user', getProperties); 
    record.save();
  }
});

Upvotes: 1

Related Questions