Doug
Doug

Reputation: 1714

Ember createRecord not creating an id

I'm trying to create a "note" record with createRecord. When I pass it into my action, it properly creates the record, but only creates the "body" attribute I pass in, and not the id or timestamps. It does, however, create these attributes after I refresh. My problem is that I want it to create these as soon as I click my "create" button, so I can sort in descending order, and be able to delete the note without having to refresh each time.

My controller:

import Ember from "ember";

export default Ember.ArrayController.extend({
  actions: {
    newNote: function() {
      var body = this.get('noteCopy');
      var note = this.store.createRecord('note', { body: body });
      this.set('noteCopy', '');
      note.save();
    },
    deleteNote: function(id) {
      this.store.find('note', id).then(function(note) {
        note.deleteRecord();
        note.save();
      });
    }
  }
});

My template:

{{textarea placeholder="Add a note!" value=noteCopy class='newNoteArea' 

autofocus=true}}<br>
<button class='createNoteButton'{{action 'newNote'}} style='font-size:2em'>Save Note</button><br><br>
<br>
{{#each note in model}}
  <div class="noteShow">
      {{note.body}}<br>
  <img src="assets/erase.gif" alt="" class='deleteNoteButton'{{action 'deleteNote' note.id}} style='width:4em'/>
</div>
{{/each}}
{{outlet}}

My server does the sorting properly once the note creates the timestamps attributes... But since I get

id: null, body: "some body", created_at: undefined, updated_at: undefined

every time I create a new note, it doesn't do anything it's supposed to, until I refresh. It occurred to me that this may be a problem with promises, but after trying to implement some .success() and .then() lines, I have a feeling this isn't the case.

Forgive me if this is a newbie question, but I'm still quite new to Ember. Any input is appreciated. Thanks!

Upvotes: 2

Views: 1171

Answers (1)

sunapi386
sunapi386

Reputation: 1357

The id is given to you by the API server you POST to. You can retrieve the id after the creation was successful.

var newJob = jobController.store.createRecord('job', {
  status: 'requested',
  message: '',
});
console.log(newJob);

newJob.save().then(() => {
    console.log('Job ID ', newJob.id, ' created.');
  }.bind(jobController), (err) => {
    console.log(err.message);
  }.bind(jobController)
);

Upvotes: 1

Related Questions