Ember data commit() - ember.js

This has been asked multiple times, however nothing has worked for me.
App.CatalogAddRoute = Ember.Route.extend({
// other stuff ...
actions: {
save: function() {
this.get('store').createRecord('category', {
category_id: 4,
category_name_fr_sh: "wat"
//... other properties
});
this.get('store').commit();
this.get('target.router').transitionTo('catalog.index');
}
}
});
I can see in my Ember toolbar that my createRecord did work. One more Category has been add to my controller. But the commit() always throws me the same error:
Object [object Object] has no method 'commit'
Anyone has a hint here at what could be wrong ?

You call save on the model instead of commit on the store, it's possible you're looking at old documentation, or documentation for a different version of ED than that of which you're using, see https://github.com/emberjs/data/blob/master/TRANSITION.md for the changes made when they went to 1.0 beta releases
actions: {
save: function() {
var record = this.get('store').createRecord('category', {
category_id: 4,
category_name_fr_sh: "wat"
//... other properties
});
record.save();
this.get('target.router').transitionTo('catalog.index');
}
}

Related

Why does my Ember computed property on hasMany relationship not update?

I have an Ember Data model as:
export default DS.Model.extend({
name: DS.attr('string'),
friends: DS.hasMany('friend',{async:true}),
requestedFriendIds: Ember.computed('friends',function(){
return this.get('friends').then(function(friends){
return friends.filterBy('status','Requested').mapBy('id');
});
})
});
I have a route setup that uses it:
export default Ember.Route.extend({
model: function(params){
return Ember.RSVP.hash({
memberProfile:this.store.find('member-profile', params.memberprofile_id).then(function(memberProfile)
{
return Ember.RSVP.hash({
requestedFriendIds:memberProfile.get('requestedFriendIds'),
UserId:memberProfile.get('user.id'),
Id:memberProfile.get('id')
});
}),
});
}
});
},
And htmlbars that utilize the route model. My computed property is always correctly called on a reload, but isn't refreshed on a user action 'Add Friend', which changes the store by adding a friend and the profile.friends' record like this:
actions:
{
addFriend:function(profile_id,)
{
this.store.findRecord('member-profile',memberProfile).then(function(member){
var friend = this.store.createRecord('friend',
{
member:member,
status:'Requested',
timestamp: new Date(),
});
friend.save();
member.get('friends').pushObject(friend);
member.save();
}.bind(this));
}
}
Some notes: I've tried the computed property on 'friends','friends.[]'. My code base is Ember 2.0.1, with Ember.Data 1.13.12, and as such 'friends.#each' is deprecated. The underlying data is correctly updated in the backing store (EmberFire). I've debugged into EmberData and I see that the property changed notifications invalidation code is called. This is only a selection of the code...
What am I missing...? Is there a better way to approach this?
I think you should watch friends.[] instead of only friends:
requestedFriendIds: Ember.computed('friends.[]',function(){
return this.get('friends').then(function(friends){
return friends.filterBy('status','Requested').mapBy('id');
});
})
And you could probably put your action in your route and manually refresh model (it might be issue with promise result not binding to changes in CP). So, in your route:
actions: {
addFriend(profile_id) {
this.store.findRecord('member-profile', memberProfile).then(member => {
let friend = this.store.createRecord('friend',
{
member:member,
status:'Requested',
timestamp: new Date()
});
friend.save();
member.get('friends').pushObject(friend);
member.save();
this.refresh();
});
}
}
The most important part is using this.refresh() in Ember.Route.

Ember: How to cleanly replace model data and have progress indicators

I have a certain route that shows a list of projects, and it gets initial data from my RESTAdapter based on who the user is.
I am now implementing a search function that will issue a new API call so the user can get records besides the default ones for them, and the response should replace the model for that route. I have all that working, but I'm not sure how to do a loading or progress indicator (as the response from the database could potentially take 5-10 seconds depending on the amount of data). I know about loading substates, but in this case I'm not transitioning between routes. I just want to have at minimum a spinner so the user knows that it's working on something.
Would anyone that's done this before be willing to share how they handled a)replacing the model with new data, and b)keeping the user informed with a spinner or something?
Form action called when user clicks the Search button
searchProjects: function() {
var query = this.get('queryString');
if (query) {
var _this = this;
var projects = this.store.find('project', {q: query});
projects.then(function(){
_this.set('model', projects);
});
}
}
a) replacing the model with new data
You don't need to do anything. If you sideload records properly from the backend, Ember will automatically update them on the frontend.
b) keeping the user informed with a spinner or something
The loading substate is an eager transition. Ember also supports lazy transitions via the loading event.
You can use that event in order to display the spinner.
Here's an example from the docs:
App.ApplicationRoute = Ember.Route.extend({
actions: {
loading: function(transition, route) {
showSpinner();
this.router.one('didTransition', function() {
hideSpinner();
});
return true; // Bubble the loading event
}
}
});
UPD1
I need to do at least what I'm doing right? Setting the model to the response?
You need to reflect the search in the URL via query params. This will let the router automatically update the model for you.
what I would put in showSpinner to affect stuff on the page (like, can I use jQuery to show or hide a spinner element?), or show the actual loading substate.
I would set a property on that page's controller:
App.IndexRoute = Ember.Route.extend({
queryParams: {
search: {
refreshModel: true
}
},
model () {
return new Ember.RSVP.Promise( resolve => setTimeout(resolve, 1000));
},
actions: {
loading (transition, route) {
this.controller.set('showSpinner', true);
this.router.one('didTransition', () => {
this.controller.set('showSpinner', false);
});
return true;
}
}
});
App.IndexController = Ember.Controller.extend({
queryParams: ['search'],
search: null,
showSpinner: false,
});
Demo: http://emberjs.jsbin.com/poxika/2/edit?html,js,output
Or you could simply put the spinner into the loading template, which will hide obsolete data:
http://emberjs.jsbin.com/poxika/3/edit?html,js,output
Or you could put your spinner into the loading template:
Just in case others want to see, here's my working code based on #lolmaus's answers.
These Docs pages were helpful as well
Route's queryParams and Find method
Controller
//app/controllers/project.js
export default Ember.ArrayController.extend({
queryParams: ['q'],
q: null,
actions: {
searchProjects: function() {
var query = this.get('queryString');
if (query) {
this.set('q', query);
}
}
}
})
Route
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model: function(params) {
if (params.q) {
return this.store.find('project', params);
} else {
return this.store.findAll('project');
}
},
queryParams: {
q: {
refreshModel: true
}
},
actions: {
loading: function(/*transition, route*/) {
var _this = this;
this.controllerFor('projects').set('showSearchSpinner', true);
this.router.one('didTransition', function() {
_this.controllerFor('projects').set('showSearchSpinner', false);
});
return true; // Bubble the loading event
}
}
});
My issue now is that when I use the parameter query, it works great, but then if I clear the query (with an action, to effectively "go back") then the records fetched by the query stay in the store, so when it does a findAll() I have both sets of records, which is not at all what I want. How do I clear out the store before doing findAll again?

How to remove a newly created model using Ember data?

I'm implementing a view for creating a new user.
App.UserNewRoute = Ember.Route.extend({
model : function(params) {
return this.store.createRecord('user');
}
});
On the UserNewController there is a method which is triggered if the user presses cancel.
App.UserNewController = Ember.ObjectController.extend({
//... code
actions: {
//.. other actions
cancel: function(){
var model = this.get('model');
model.destroyRecord();
this.transitionToRoute('users');
}
}
});
I'm always getting the following error:
Uncaught Error: Attempted to handle event `willCommit` on <App.User:ember751:null> while in state root.deleted.saved.
I've tried using an alternative:
model.deleteRecord();
model.save();
I get the same error.
What am I doing wrong?
The issue might have to do with the fact that model.destroyRecord() returns a promise and that you are transitioning before that promise fulfilled. I have been using the following:
var model = this.get('model');
var _this = this;
// assuming you are working with a new model and not on say an edit page
// this will delete the new record and once the promise returns will transition routes
if (model.get('isNew')) {
model.destroyRecord().then(function() {
_this.transitionToRoute('route name');
}
}
So that the transition only happens once the promise has been fulfilled. I am still an ember scrub but I figured it wouldn't hurt.
According to this https://github.com/emberjs/data/issues/1669, the issue might be already fixed in newer Ember versions. I'm using Ember version 1.5.1 and Ember-Data version 1.0.0-beta.6
The workaround was to do a dirty check.
var model = this.get('model');
model.deleteRecord();
if (model.get('isDirty')) {
model.save();
}
this.transitionToRoute('users');

How to Add Child Record to Existing Parent Record?

I've been googling and scouring Stack Overflow for some sort of hint on this subject but the information is scattered at best.
I'm trying to Create a new Child Record (Comment) and save it to an existing Parent Record (Post). I am using Ember-Model, rather than Ember-Data, but any tips or pointers would be greatly appreciated.
At the moment, I've been successful creating a new, embedded Comment but only when it is created with a new Post record. So:
How do I go about loading/retrieving the currently loaded Post(parent record) in order to apply Comments (child records) to it?
I've been reading up on controller dependencies, using needs: and this.controllerFor and this.modelFor in order to have access to another controller/model's content but have been unable to wire these things together into something meaningful.
Anyway, here is what I've whittled my application code down to, in the hopes I might be able to stumble into the proper way of doing this...
Routes
App.Router.map(function() {
this.resource('post', { path: '/:post_id' }, function() {
this.resource('comments', { path: '/comments'} );
});
});
I removed all the other resources & routes, so I'm left with App.Post, App.PostIndex, and App.Comments. I think my routes are the issue here, I assume I'm not properly implementing the methods to use the loaded Post record in my Comments route.
App.IndexRoute = Ember.Route.extend({
model: function() {
return App.Post.find();
},
setupController: function(controller, model) { // I'm not certain if this
controller.set('content', model); // setupController is needed?
}
});
App.PostRoute = Ember.Route.extend({
model: function(params) {
return App.Post.find(params.post_id);
},
setupcontroller: function( controller, model) { // again, unsure if this
this.controllerFor('post').get('comments'); // is correct.
controller.set('content', comments);
}
});
App.CommentsRoute = Ember.Route.extend({
afterModel: function() {
this.set('post', this.modelFor('post'));
},
setupcontroller: function( controller, model) {
this.controllerFor('post').get('comments');
controller.set('content', comments);
}
});
Controller
App.CommentsController = Ember.ArrayController.extend({
needs: "post",
actions: {
addComment: function() {
var post = App.Post.create({
title: 'static post title'
});
post.get('comments').create({
message: 'static message'
});
post.save();
}
}
});
This is my current Comments Controller, which can create a new Post with an embedded Comment. I've found and been given numerous examples in which to create the Comment, but none seem to work for me. Basically, I'm struggling with defining the var post = ... as the currently loaded record. I've implemented various approaches in an attempt at trial & error. Thus far I have attempted:
var post = App.Post.create();, returns property undefined, as this would create a new record. However, I gave it a shot as every example i saw related to this defined their record as such.
var post = this.get('post');, returns a cannot call 'get' on undefined. I've tried using this method of defining my current post on both the Comments controller and Post controller.
var post = this.get('controllers.post.content);, returns a 'cyclic error' from the backend I'm using.
var post = App.Post.find();, returns a cannot call 'get' on undefined.
var post = App.Post.find(1);, Again, returns a cannot call 'get' on undefined. Figured I'd give it a shot because this is one of those recurring examples people provide. The backend I use applies its own ID to each record, and I'm unsure if I would be able to/how to have the .find() method use a dynamic ID value and retrieve only the model I just loaded.
I'm guessing that I'm not properly setting up my Routes and Controller dependencies?
If anyone has a suggestion, relevant link, or fix I would be very grateful.
This one (seemingly simple) issue/use case has me at wit's end at this point.
Try this (works pre beta 2):
App.CommentsController = Ember.ArrayController.extend({
actions: {
addComment: function() {
this.content.createRecord({
message: 'static message'
});
}
}
});
Ember Data Beta 2 and later:
App.CommentsController = Ember.ArrayController.extend({
needs: ["post"],
actions: {
addComment: function() {
var post = this.get('controllers.post');
var comment = this.get('store').createRecord('comment', {
message: 'static message',
post: post
});
comment.save().then(function() {
post.addObject(comment);
// You may or may not need to save your post, too. In my case my backend handles
// the inverses of relationships (if existing), so there's no need. We still need
// to do this for Ember, though
});
}
}
});

Duplicate null-id records in ember-data

I'm using ember 1.0 and ember-data 1.0.0 beta 1. I have the following routes and controller to create and save simple notes ('AuthenticatedRoute' is just a custom made route for logged-in users):
App.Note = DS.Model.extend({
title: DS.attr(),
author: DS.attr(),
body: DS.attr(),
createdAt: DS.attr()
});
App.NotesRoute = App.AuthenticatedRoute.extend({
model: function() { return this.store.find('note'); },
});
App.NotesNewRoute = App.AuthenticatedRoute.extend({
model: function() {
return this.store.createRecord('note');
}
});
App.NotesNewController = Ember.ObjectController.extend({
actions: {
save: function() {
var self = this, model = this.get('model');
model.set('author', localStorage.username);
model.set('createdAt', new Date());
model.save().then(function() {
self.get('target.router').transitionTo('notes.index');
});
}
}
});
When I save a new note everything works as expected. But when I navigate away from the notes route and then back into it, the notes list is populated with a duplicate entry. One entry has an id and can be edited, deleted etc, the other has all the data of the first entry except the id attribute is null. It seems to me ember-data keeps the newly created record (that hasn't been committed to the database and thus has no id yet) alive even when the record becomes committed but I am uncertain as to why. When I reload the page, the list is correctly displayed, no duplicates appear. What am I doing wrong?
For the record, I am using mongodb so I use a custom serializer to convert '_id' attributes to ember-data friendly 'id's, essentially copied from here:
App.NoteSerializer = DS.RESTSerializer.extend({
normalize: function(type, hash, property) {
// normalize the '_id'
var json = { id: hash._id };
delete hash._id;
// normalize the underscored properties
for (var prop in hash) {
json[prop.camelize()] = hash[prop];
}
// delegate to any type-specific normalizations
return this._super(type, json, property);
}
});
I should also mention that this problem existed in ember-data 0.13 as well.
It was a stupid mistake in my RESTful server. I was responding to POST requests with a 204 (empty) response instead of what ember-data expected, that is a 201 ("created") response with the newly created record as the payload. This post made me realize it.
It would be nice though to include this information in the official REST adapter documentation.
That is certainly strange behaviour indeed. Unfortunately I'm not able to explain why you're experiencing this, however:
You can use the willTransition callback in the actions object in your Route to ensure that when it is transitioned away from, if NotesNewController's content property is dirty (i.e. has not been persisted yet), it will have its transaction rolled back.
App.NotesNewRoute = App.AuthenticatedRoute.extend({
model: function() {
return this.store.createRecord('note');
},
actions: {
willTransition: function (transition) {
var model = this.controllerFor('notesNew').get('content');
if (model.get('isDirty') === true) {
model.get('transaction').rollback();
}
return this._super(transition);
}
}
});