A method similar to ModelName.new (as in Rails)

Contacts Route

App.ContactsNewRoute = Ember.Route.extend({

 model: function () {
    return App.Contact.createRecord({name: '', email: ''});
  },
  actions: {
    save: function () {
      this.get('store').commit();
      this.transitionTo('contacts');
    }

  }
});

contacts/new.hbs

<form {{action 'save' on="submit"}}>
    {{view  Ember.TextField valueBinding="name" placeholder="name" required="true" }}
    <br />
    {{view  Ember.TextField valueBinding="email" placeholder="email" required="true" }}
    <br />
    <button class="btn btn-success" type="submit">Save</button>
    <button {{action 'cancel' }} class="btn" >Cancel</button>

</form>

This works fine, but I have to initialize an empty model object in the new page everytime like this

App.Contact.createRecord({name: '', email: ''});

What if there are too many attributes? Wish there existed something similar to Contact.new as in Rails.

Something like this would be really cool or is there any already ?

App.Contact.newRecord();

The ContactsNewController, being an Ember.ObjectController, will proxy all missing property lookups and sets to the underlying model, which is your App.Contact record. That means there is no need to define the empty attributes, as you type into the text fields, the values are going to be set on your App.Contact object, so when you submit the form, it will “just work”.

I’m not 100% sure without actually checking but I think this should work.

1 Like

@vysakh0 are you not on a recent version of Ember Data? With recent versions this will work fine:

App.ContactsNewRoute = Ember.Route.extend({
 model: function () {
    return this.get('store').createRecord('contact');
  },
  // ...snip...
});
1 Like

OMG! Too much magic stuff, how do I know more about these?

I hear you :slight_smile:

There is a section in the official guides on ember-data models but it is still somewhat lacking (save is not mentioned, e.g). There is a transition doc in the repo which answers most of the basic questions.