I am working with two models that have a many to many relationship - 'recipe' and 'tag':
App.ApplicationAdapter = DS.FixtureAdapter.extend({});
App.Recipe = DS.Model.extend({
title: attr('string'),
source: attr('string'),
notes: attr('string'),
isFavourite: attr('boolean', {defaultValue: false}),
tags: hasMany('tag', { async: true })
});
App.Tag = DS.Model.extend({
name: attr('string'),
recipes: hasMany('recipe', { async: true })
});
Within my template, there is an input for adding tags to a recipe. Users can add one tag or multiple by separating them with commas.
{{input type="text" enter="AddTags" placeholder="add a tag (or two!)"}}
This triggers the 'AddTags' function in my RecipeController:
App.RecipeController = Ember.ObjectController.extend({
actions: {
AddTags: function(tags){
var store = this.store;
var thisRecipe = this.get('model');
var thisRecipeTags = thisRecipe.get('tags');
var addedTags = tags.split(',');
for (i = 0; i < addedTags.length; i++) {
tag = store.createRecord('tag', {
name: addedTags[i]
});
thisRecipeTags.addObject(tag);
}
}
}
});
Although the current setup works well, I would like to enhance it so that a new tag is only created if a tag with the same name doesn't already exist:
AddTags: function(tags){
var store = this.store;
var thisRecipe = this.get('model');
var thisRecipeTags = thisRecipe.get('tags');
var addedTags = tags.split(',');
for (i = 0; i < addedTags.length; i++) {
// If exisiting tag where name == addedTags[i]
tag = existing tag object here
// Else create a new tag
tag = store.createRecord('tag', {
name: addedTags[i]
});
thisRecipeTags.addObject(tag);
}
}
Any suggestions on how I can achieve this?
Update: A JS bin with the code can be found here: http://jsbin.com/kixexe/1/edit?js,output