lundi 13 avril 2015

How to add a new record (in Ember.js) with belongsTo relationship, check if the belongsTo record exist and add that too if it doesn't.

I have two models: Post and Date.



App.Post = DS.Model.extend({
date: DS.belongsTo('date', {async: true})
});

App.Date = DS.Model.extend({
when: DS.attr('date'),
posts: DS.hasMany('post', {async: true}),
});


While creating a new post, I need to check if the date user entered already exists in the Date model. If not, a new Date record also needs to be created.


Adding a new post is happening in AddController. I am guessing AddRoute needs both models (post and date) and both controllers set up as follows. Struggling with how to access controllers and models in the AddController (commented below 1,2,3)



App.AddRoute = Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
post: this.store.createRecord('post'),
dates: this.store.findAll('date')
});
},
setupController: function(controller, model) {
controller.set('model', model.post);
controller.set('dates', model.dates);
}
});

App.AddController = Ember.Controller.extend({
d:'', //the date user inputs
actions: {
createPost: function() {
var controller = this;
console.log(controller.get('d'));
controller.get('model').save().then(function(){
// 1. How to check if date already exists? Something like:
// this.store.find('date', controller.get('d'));
// 2. If date already exists, how to addObject to posts?
// controllerOfDate.get('model.posts').addObject('post');
// else (if it's a new date)
// 3. How to create new record in date:
// this.store.createRecord('date', {when: controller.get('d')});
// controllerOfDate.get('model.posts').addObject('post');

});
}
}
});




Aucun commentaire:

Enregistrer un commentaire