This is how my products.index
looks:
When I click on "Create product" link. It sends me to /products/new
. I see a form there, but I dont submit it, instead I click on the "Cancel" button. I have an action in my controller that redirects me to the products.index
page.
actions: {
cancel: function() {
this.transitionToRoute('products.index');
return false;
}
}
In /products
, I see:
Which is an empty product... The DB in the API has no products. I refresh the page, and the empty product goes away. Whats going on here?
The full code:
// app/routes/products/index.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.find('product');
}
});
// app/routes/products/new.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.createRecord('product');
},
});
// app/controllers/select-addresses/new.js
export default Ember.ObjectController.extend({
actions: {
cancel: function() {
this.transitionToRoute('products.index');
return false;
}
}
});
// app/templates/products/index.hbs
<h1>Products index</h1>
<p>{{#link-to 'products.new'}}Create product{{/link-to}}</p>
<ul>
{{#each}}
<li>
{{#link-to 'products.show' this}}<strong>{{name}}</strong>{{/link-to}}
<br />Description: {{description}}
<br />Amount in cents: {{amountInCents}}
<br />{{link-to 'Edit' 'products.edit' this}} · <a href="#" {{action "delete" this}}>Delete</a>
<br /><br />
</li>
{{/each}}
</ul>
// app/templates/products/new.hbs
<h1>Add a new friend</h1>
<form {{action "save" on="submit"}}>
<p>
<label>Name:
{{input value=name}}
</label>
{{#each error in errors.name}}
<br />{{error.message}}
{{/each}}
</p>
<p>
<label>Description:
{{input value=description}}
</label>
{{#each error in errors.description}}
<br />{{error.message}}
{{/each}}
</p>
<p>
<label>Amount in cents:
{{input value=amountInCents}}
</label>
{{#each error in errors.amountInCents}}
<br />{{error.message}}
{{/each}}
</p>
<p>
<label>Status:
{{input value=status}}
</label>
{{#each error in errors.status}}
<br />{{error.message}}
{{/each}}
</p>
<input type="submit" value="Save"/>
<button {{action "cancel"}}>Cancel</button>
</form>
{{outlet}}
Use ember-data-route and then you should do
{{#each product in model}}
{{#unless product.isNew}}
{{product.name}}
{{/unless}}
{{/each}}
If you don't want to use ember-data-route
, you can always use resetController and do model.deleteRecord()
.
// app/routes/products/new.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.createRecord('product');
},
resetController: function (controller, isExiting) {
var model = controller.get('model');
if (isExiting && model.get('isNew')) {
model.deleteRecord()
}
}
});
For a more in-depth version see what ember-data-route is doing.