saving form with associated model - ember.js

It seams simple, but I'm stuck on this one. I have a single controller, and single view dedicated to order model, which has nested client. I create empty records on setupController:
route:
ShowroomApp.OrdersRoute = Ember.Route.extend
model: ->
ShowroomApp.Order.createRecord()
setupController: (controller,model) ->
model.set("client", ShowroomApp.Client.createRecord() )
controller.set("content", model )
controller:
save: ->
#content.store.commit()
On OrdersController i have save action to commit changes made in the form. It results in two separate POST requests each one for each model, but the association doesn't build itself. Orders model saves first, and client_id is obviously null because client doesn't exists yet. Later goes Client post and saves the client, but Order model doesn't know about it and stays without client.
Is there any solution to that?
Thanks,
J

This is due to an outstanding ember-data issue - RESTAdapter: Allow new parent, child to be saved at once
Check out Tom Dale's Comment for a possible workaround. It involves manually adding support for saving both records at once.
As an alternative, you might consider adding a onCreate callback to the parent record, then creating the child in the callback. If you are ok with having a second commit() this will get the job done.

Related

How do I save all locally created records in ember / ember data?

Currently, the Ember Data filter method has been deprecated. What's the best way to approach saving all new/updated records of a particular type?
You can call save() on a RecordArray so I have been doing:
this.get('store').peekAll('record-type').save() but I'm not sure if there's some better way to go about it.
I would go with:
this.get('store').findAll('users').then((users) => {
users
.filterBy('dirtyType', 'created') // filter for unsaved records
.invoke('save'); // call the save method on each model instance
});
If you return the users object you get an array of promises that you could catch with Ember.RSVP.all(), to listen for when all the users have been saved.

Force ember data store.find to load from server

Is there a nice way to force Ember Data to load the resource from server eaven if it has it already in store ?
I have a simple show user action that do store.find('users',id) the model is loaded only once at first attempt to display a page the second time i go my model is loaded from the store which is normal ember data behaviour i know. However i need to load it each time.
edit:
the only way i found is to do this :
#store.find('user',{id: params.user_id}).then (users)->
users.get('firstObject')
however it forces me to implement a "fake" show action on my index action ...
I think this... http://emberjs.com/api/data/classes/DS.Model.html#method_reload
model.reload()
Good luck
Additionally you can call getById which will return any instance of that record that exists, or null, then call unloadRecord to remove it from the cache. I like Edu's response as well though, then I wouldn't have to worry about the record existing somewhere else. Maybe I'd use getById then reload that way any references that had a reference to the user got updated. (pardon my errant coffeescript, if it's wrong).
user = #store.find('user', params.user_id)
if (user)
#store.unloadRecord(user)
Hot off the presses, thanks to machty:
There's a new method getting added as part of the query params feature going into beta this weekend called Route.refresh()...
/**
Refresh the model on this route and any child routes, firing the
`beforeModel`, `model`, and `afterModel` hooks in a similar fashion
to how routes are entered when transitioning in from other route.
The current route params (e.g. `article_id`) will be passed in
to the respective model hooks, and if a different model is returned,
`setupController` and associated route hooks will re-fire as well.
An example usage of this method is re-querying the server for the
latest information using the same parameters as when the route
was first entered.
Note that this will cause `model` hooks to fire even on routes
that were provided a model object when the route was initially
entered.
#method refresh
#return {Transition} the transition object associated with this
attempted transition
#since 1.4.0
*/
You can do this in the setupController hook, using a promise, and the reload method mentioned by Edu.
setupController: ->
#store.find('myModel', 1).then (myModel) ->
myModel.reload()
If you are sure that records to display will change after a certain action then you can call this.refresh() method in your Route. For example:
ProductsRoute = Ember.Route.extend
model: ->
#store.find 'product',
activated: true
actions:
accept: (product) ->
if not product.get('activated')
product.set 'activated', true
product.save()
.catch (err) ->
console.log err
product.rollback()
.then =>
#refresh()
ignore: (product) ->
if not product.get('ignored')
product.set 'ignored', true
product.save()
.catch (err) ->
console.log err
product.rollback()
.then =>
#refresh()
If actions are called from child route - e.g. products/proposed - models will be reloaded for parent route and also child routes.
I think that what you are looking for is DS.Store#fetchById

Is there an issue in ember RC6?

I updated to RC6 two weeks ago, and I'm noticing an error in one of the screens in the project I'm working on. I have an ember model, which has a hasMany relation, that model as a computed property based on a property on its hasMany relationship, something like this:
notReadyToSend: function() {
return this.get('tweets').filter(function(tweet){
return !tweet.get('readyToSend');
})
}.property('tweets.#each.readyToSend')
this belongs to the tweet model:
readyToSend: function() {
//if all properties are true, then this property returns true
}.property('title', 'body', 'alreadySent', and many other properties)
and, at the time in which the data is being loaded, all the tweets are not 'ready' because you know, data is being loaded, but when the whole data is loaded, some tweets remain not 'ready' in the 'notReady' property, but they are actually 'ready' in their object, I mean, the Tweet ember model hast its 'ready' property, which also has some logic, and that property is true, but the 'notReady' property is not fired, and this happens for the last(depends how many we have, sometimes only one, sometimes two, etc) tweets.
Is anyone experiencing this issue ?
I've updated the code, but as a note, those are not the real models, but that's basically what I'm doing. the readyToSend property, gets set to true for all records, but the notReadyToSend property in the parent model, doesn't get updated, but again, this does not happen with all the records, just a few ones(and only the last in in the relationship) do not fire the parent property.
One more update, I have another property in the parent model, which also checks one property of the tweets relationship, it looks like this:
hasAtLeastOneTweetALreadySent: function() {
return this.get('tweets').findProperty('alreadySent');
}.property('tweets.#each.alreadySent')
and the 'alreadySent' property is also being observed in the 'readyToSend' property of the tweet model. And for some reason, if I just comment out that(hasAtLeastOneTweetALreadySent) property, everything works fine, do you know why this is happening ? this is weird.

Update URL after model is modified

I have a route like this "loans/:loan_id", from a link I redirect to this URL and send an unsaved Loan object as model, so the id is null, which results in the url being "loans/null", however I then save the model and it gets an ID from the server, but how can I update the URL so that it shows the new ID instead of null?
Thanks.
I assume you have a LoanNewController or something similar. Then I further assume that you are trying to transition to the new created loan object directly after you have created it, this will show an id of null since the create loan action is async and you have to wait for the loan to be created on the backend before you do the transition, so in order for it to work you could do the following:
App.LoanNewController = Ember.ObjectController.extend({
saveLoan: function() {
...
this.get('store').commit();
},
...
transitionAfterSave: function() {
if(this.get('content.id')) {
this.transitionToRoute('loan', this.get('content'));
}
}.observes(content.id)
The added observer will observe the content.id and when it is set (when the server call has returned) the transitionAfterSave will be invoked and the transition will get the content passed to it with the correct id in place.
This answer is based mainly on assumptions, since you didn't reveal that much code, but you get the point I guess.
Hope it helps.

Ember Data - rollback if navigating away from a form

My application has new / edit forms for a set of entities read from a backend.
When I open such a form, and fill out / edit some fields, then navigate away, the records appear changed in the entity lists, even though I did not commit those changes. Reloading the app (which reloads the data from the backend) fixes the issue, but is not an option.
I've tried doing some transaction rollbacks in the form view's willDestroyElement, but this seems fundamentally wrong since it gets called even after successful form submits (and actually crashes with Attempted to handle event rollback on X while in state rootState.loaded.updated.inFlight).
How would I go about ignoring all unsubmitted form changes (similar to pressing the Cancel button, which performs a transaction rollback), for any use case that involves navigating away from the forms?
Using Ember rc5, Ember Data 0.13.
When exiting the form route, check the state of the record. If its (isNew OR isDirty) and its NOT isSaving, rollback:
App.FormRoute = Ember.Route.extend({
deactivate: function() {
var model = this.controllerFor('form');
if ( (model.get('isNew') || model.get('isDirty')) && (!model.get('isSaving')) ) {
model.rollback();
}
}
});