can i createRecord() without using save()? - ember.js

I'm learning ember from the scratch and i stumbled upon something i can't quite understand:
const newNote = this.store.createRecord('note', {
content: 'once upon a time...',
});
newNote.save().then(this._redirectToNewNote.bind(this));
Is the result of createRecord in the database before saving, or is it like a dummy object? can I use createRecord without saving?

Yes. you can use it without saving, do remember it will be removed from store when you refresh page.
From ember guide
createRecord is used for creating new records on the client side. This will return a new record in the created.uncommitted state. In order to persist this record to the backend you will need to call record.save().

Related

Marking ember-data records as existing

I have a somewhat unique circumstance where I wrote a caching layer for ember-data that serializes records to localstorage. When I deserialize my cache into the ember-data models I use this.store.createRecord('model_name', cacheData);. These records I am caching have existing values on the server. This works for me fine up until I want to save() the record. The save thinks the record is a new record even though it has an "id" attribute. When save() is called a POST is made to my application server instead of a PUT. Does anyone know a way to flag records in the store as not new.
You should use store.push to add already existing records instead of store.createRecord
http://emberjs.com/api/data/classes/DS.Store.html#method_push
I couldn't find anything official, but models do have an isNew property. Since this is a read-only property, you can't set it directly, but you can set it on the currentState object like so:
var model = this.store.createRecord('model_name', cacheData);
model.set('currentState.parentState.isNew', false);
model.get('isNew') // => false
I can't speak to whether this is the best way to do it, but it should do what you're asking. Make sure you have good tests :)

Reloading a route's model with server json data and need ember-related opinion

I’m building a map with a search function. Basically, I’d like to store objects from the server within my ember app so that whenever I search for something that collection updates itself with the results from the server so the related view updates itself. It’s all on one page.
So far I have an Application Controller, and a Results ArrayController. Data is shown from the Results Controller. Now I’d need that when a search is requested, it gets JSON from the server and updates the results collection.
First question would be:
How would you build that?
I did a v1 with jQuery only and started a new one with Ember but I’m lost as of how structure-wise should I build it.
I built a small jsbin based on what I have here: http://emberjs.jsbin.com/IYuSIXE/1/
Second question:
How would I change a route's model content? Am I going in the wrong direction?
Thanks a lot
You can do both 1 and 2 with query params, check the documentation here https://github.com/alexspeller/website/blob/a96d9afe4506454b155cc64299e86e558ce3c9f1/source/guides/routing/query-params.md
When your route calls the model it will pass the query params, you can do your search against them
model:function( params, queryParams, transition ) { callToYourBackedEndWithQueryParams}
Second question: How would I change a route's model content? Am I
going in the wrong direction?
When the search is requested, in an action you can call this.transitionTo({queryParams: {sort: 'asc'}});, that will fire up again the model hook and you can do the query against your server again.
What I was looking for is a way to change the model on-the-fly.
So basically if I have this:
App.ResultsRoute = Ember.Route.extend({
model: function() {
// empty array that will contain results
return [];
}
});
I can do this to set the content of the model:
this.get('model').setObjects([{}, {}, {}]);
That way I can dynamically play with the models, load them with objects coming from almost anywhere.

Ember Data - destroy model from controller

I have a Lead model defined with DS.Model and I noticed something weird when I was working with creating my app. When the REST resource doesn't return a resource in subsequent calls, the old data stays around. I tried to solve this by doing:
var model = this.get('model');
model.forEach(function(model) {
model.destroy();
});
However, nothing happens. I have searched around but can't find the proper way to clear out a specific model cache and then refresh it with find(). I am using ember data 0.13
Please try this:
model.deleteRecord();

EmberJS Model find not up-to-date with underlying store

For a simple overview screen I have a developed a route that sets up a controller that does an App.Location.find().
App.LocationsIndexRoute = Ember.Route.extend({
setupController: function(controller) {
controller.set('content', App.Location.find());
},
renderTemplate: function() {
this.render('locations.index',{into:'application'});
}
});
I naively assumed that this would simply go to the store and fetch me all the records, giving me an up-to-date view of the records.
Apparently not....
When an external process starts removing records from the database,
the App.Location.find() keeps on returning these deleted records.
(although the REST call doesn't show them anymore)
If an external
process starts adding records to the database, the
App.Location.find() picks them up.
If I delete the records form
within the Ember app itself the model is correctly updated.
How should I deal with this in my Ember app ? I'd like to have an up-to-date view on whatever is in my database. Right now I need to refresh the page (F5) to get an up to date view. Using the linkTo helpers shows me the stale data.
This seems to be yet another trivial thing that I completely missed in EmberJS. Is it somewhere mentioned in the docs why it behaves like that ? I guess there is a valid philosophy behind this behavior.
My overview screens is simply interested in showing the most up-to-date data. If a record is no longer in the DB the model should not return it anymore.
I've added a sample project in Github that is having this issues.
Try unloading all of the data from the store before you call find():
this.store.unloadAll('widget');
this.store.find('widget');
That will fully refresh your store to reflect what's on your server.
Have you tried App.Location.query() instead of App.Location.find()?

Revert change to ember data model

Is there a way to revert a change to an Ember Data model easily?
I have a model bound to an edit view. This view enables the user to cancel editing, at which point I'd like to revert the changes to the model. Is there an easy way to do this without cloning all the values off the side?
Starting from Ember Data version 2, there are not transactions anymore, but you can reset models to their last status before saved editions with:
model.rollbackAttributes();
Ember Data supports the concept of transactions. We can create a transaction and assign Ember data records to them and if we want to undo the changes we can call the transactions rollback() method. Also if we do not create an explicit transaction the records are assigned to a default transaction which can be rolled back by calling the rollback() method on the DS.store object itself.
The name of the default transaction is named 'defaultTransaction'. In fact, when Embers commits, it uses this default transaction. I can't use directly rollback on the store directly.
Instead of using store.rollback, you should have something like:
store.get('defaultTransaction').rollback()
or (if you are in a router event manager)
event.get('store.defaultTransaction').rollback()
You could also do a rollback on the model itself if it is in an "isDirty" state.
this.get('model').rollback();
Example
export default Ember.ObjectController.extend({
actions: {
cancelEditModel: function(){
this.get('model').rollback();
this.transitionToRoute('...');
return false;
}
}
});