mercredi 21 février 2018

Ember - create default record if model is empty

I have a simple User model, with two fields: name and user_id

When the app starts, I want to check if my User model contains at least one record - if not, I want to create a default "admin" user automatically.

I have the following code in my application route:

model() {

let user = this.store.findAll('user'); // find all users

let record = user.then(function(result) { 
    let first = result.get('firstObject'); // check if we at least one user
    if (first) { // if true, then we have at least one user
      let user_id = first.get('user_id'); // get the first user's id
      // do some more stuff here
    }
    else {
      console.log("no record found"); // no user found, let's create our default user
      let user = this.store.createRecord("user", { // <-- THIS DOESNT WORK - where can I create my record?
        user_id: 1,
        name: 'admin'
      });
    }
});

}

This code works, except that I can't call this.store inside my promise function, since this now belongs to the function.

Would it be better to create an action, and then call that action in my else statement? But then, how would I trigger that action from the model itself?

Any ideas would be helpful at this point. It feels like I'm misunderstanding some fundamental law of Ember (again).




Aucun commentaire:

Enregistrer un commentaire