In Ember, I have two models, Product and Genre, with Product having many Genres, set up like this.
App.Product = DS.Model.extend({
title: DS.attr(),
genres: DS.hasMany('genre')
});
App.Genre = DS.Model.extend({
name: DS.attr(),
product: DS.belongsTo('product')
});
Genres can be created on a separate page, and then multiple genres can be set for a product on the product page by selecting from a select element, with the option to add extra genres. The controller and template are set up as below.
App.ProductController = Ember.ObjectController.extend({
availableGenres: function() {
return this.store.findAll('genre');
}.property(),
actions: {
saveProduct: function() {
var product = this.get('model');
product.save();
},
addGenre: function() {
var product = this.get('model');
var genre = this.store.createRecord('genre');
product.get('genres').pushObject(genre);
}
}
});
And the template:
{{view "select" content=availableGenres value=genre.name}}
<button {{action 'addGenre'}}>Add Genre</button>
The way this is currently set up, it creates a new genre, which is incorrect. What I can't work out is how I am supposed create a new genre select in the view, without creating a new genre.
How do I create a new select for a genre without creating a new genre? Setting it to the first genre from possibleGenres would suffice, but I am stuck working out how to select the first genre within that function. I'm fairly new to Ember, so any help is much appreciated!
Aucun commentaire:
Enregistrer un commentaire