I have created a comment model and trying to fetch all comments records. But I need a meta info total comments which is getting as a separate attribute outside comments array.
I am using Ember store.query to fetch records from rest service(I tried store.findAll, but it is giving me only record array of comments in promise response. Is it possible to modify that?). I am getting the records with total comments(meta) while using store.query(), but that record array is not getting updated when we save new records.
After doing some analysis I found that we can use filter for loading the live record, but filter is now deprecated in Ember(Ember 2.5.1). From the documentation It is clear that we can use ember-data-filter for loading live record. But I am confused to use that addon(Mentioned like it has some memory leakage issue) and not sure whether I will get meta information from response. Is there is any other way to fetch live records with meta information from the response.
Anyone please suggest a solution
After doing some analysis, I found a solution to access meta data using store.findAll(). We can use typeMapFor in the findAll response to get the meta info in the response
store.typeMapFor(response.type)
Full code below,
store.findAll("comment").then(function(response) {
var meta = store.typeMapFor(response.type);
// your meta info will be in meta.metadata
// var totalComments = meta.metadata.totalComments;
});
And the response record array is liveRecords which will get updated automatically, if we save new records.
store.query("comment").then(function(response) {
var meta = response.get("meta");
// We will get meta like this but reponse record array is not a liveRecords
});
Response getting from store.query() is just a recordArray (not liveRecords) which will not get updated with new records
If you want an array of all records that updates as new records are populated you can use peekAll which returns a live record array.
Added Code sample:
loadRecords: function (){
this.set('allComments', store.peekAll('comment'));
this.store.findAll('comment');
},
recordCount: Ember.computed.alias('allComments.length')
Related
I use django-multiselectfield package in my project and based on its docs I use MultipleChoiceField in my serializer:
class InsCatSerializer(serializers.ModelSerializer):
levels = fields.MultipleChoiceField(choices=LEVEL)
when I send a request with raw JSON in postman that works fine
"levels": ["INTERMEDIATE", "ADVANCED"]
But I need to use form data because I have files and images in my request!
I try this way:
levels:INTERMEDIATE
levels:ADVANCED
but just saved the last element ( ADVANCED in this example )
any suggestion to solve?
Json Array and Form data can't work together. Please stringify your array or don't use form data at all.
Read more: JS, how to append array in FormData?
So in rails we could find a record by name, id etc, similarly i want to do in ember without making a server request
I have a model called person{id, name}. If i want to peek a record by id i do this:
this.get('store').peekRecord('person', id)
which gives me the record based on id, but now i want to peek a record with a particular name, i tried something like this:
this.get('store').peekRecord('person', {name: "testname"})
which dose not seem to work.
i need a way peek a record using just the name
You can only peekRecord using the unique identifier for the model, which is id property. If you do want to make a request then queryRecord is what you want. but you don't want to make a request so the only choice is peekAll and filter the result,
let allRecord = this.get('store').peekAll('person');
let filteredResult = allRecord.filterBy('name','testname');
//filteredResult is an array of matching records
I have the following code:
var msg = this.store.createRecord({text:'first title', createdAt: "2015-06-22T20:06:06+03:00" })
this.get('model.content').pushObject(msg);
msg.save();
We create new record. Then push in it to the model to display. It worked perfectly in 1.9 version but after upgrading it to the newest 1.13 it breaks and shows this error:
TypeError: internalModel.getRecord is not a function
after some researches I came out to this solution
this.get('messages.content').unshiftObject(message.internalModel);
and it partially help. Now I have two problems:
I'm not confident if using private ember data api is a good idea
I have an annoying delay between adding record to the model and
rendering it on the screen. More than that if I don't call
msg.save(); the record isn't rendered. So as far as I understood it
waits until we have response from server and only then renders it.
But I need opposite behaviour - I need to show the record first and
then save it(showing the saving state for the user), this way user
thinks that everything goes extrimely fast.
One possible solution without resorting to private API is to use toArray() (github issue):
var array = this.get('messages').toArray()
array.addObjects(this.get('messages'))
array.addObject(msg)
this.set('messages', array)
Before 1.13:
this.get('content').pushObjects(messages);
After 1.13:
messages.forEach(functio(message) {
this.get('model.content').pushObject(message._internalModel);
});
I would make all return models to array then, add array to this array
setPeople:function(){
this.set('people',this.get('content').toArray())
}.observes('content')
then, find more person models, to array
getMoreUsers(){
var self = this;
this.set('offset', this.get('offset')+1);
self.store.findAll('person').then(function(people){
self.get('people').pushObjects(people.toArray());
});
I'm wonder why my template doesn't get updated after createRecord when using findQuery to fetch data.
When changing this return this.store.findQuery('timetracking', {year: year, month: month, user_id: user_id}); to return this.store.find('timetracking'); the template gets updated with my new records.
I don't want to fetch all records to save bandwith, but when using only find/findQuery with query params, my newly created records doesn't show up in my template.
Do I have to do a "force" reload? And how to do this?
Update
The Ember inspector shows the new records.
findQuery puts the job of filtering on the server's back. Ember Data assumes that the results that were returned are the only results that are associated with that collection. find with no query or id (findAll) will always return all records found in the store, because it realizes you weren't looking for any filtered set, if you create a new record it gladly knows to include it in all of the available records. You can manually push a record into a collection of records using pushObject.
// assuming you're in the context of your `findQuery` results, and they are the model
var model = this.get('model'),
record = this.store.createRecord('timetracking', {...});
model.pushObject(record);
Im playing a little bit with heavy-client app.
Imagine I have this model:
class Category(models.Model):
name = models.CharField(max_length=30)
color = models.CharField(max_length=9)
Im using knockoutjs (but I guess this is not important). I have a list (observableArray) with categories and I want to create a new category.
I create a new object and I push it to the list. So far so good.
What about saving it on my db? Because I'm using tastypie I can make a POST to '/api/v1/category/' and voilĂ , the new category is on the DB.
Ok, but... I haven't refresh the page, so... if I want to update the new category, how I do it?
I mean, when I retrieve the categories, I can save the ID so I can make a put to '/api/v1/category/id' and save the changes, but... when I create a new category, the DB assign a id to it, but my javascript doesn't know that id yet.
in other words, the workflow is something like:
make a get > push the existing objects (with their ids) on a list > create a new category > push it on the list > save the existing category (the category doesnt have the id on the javacript) > edit the category > How I save the changes?
So, my question is, what's the common path? I thought about sending the category and retrieving the id somehow and assign it to my object on js to be able to modify it later. The problem is that making a POST to the server doesn't return anything.
In the past I did something like that, send the object via post, save it, retrieve it and send it back, on the success method retrieve the id and assign it to the js object.
Thanks!
Tastypie comes with an always_return_data option for Resources.
When always_return_data=True for your Resource, the API always returns the full object event on POST/PUT, so that when you create a new object you can get the created ID on the same request.
You can then just read the response from your AJAX and decode the JSON (i dont know about knockout yet).
see the doc : http://readthedocs.org/docs/django-tastypie/en/latest/resources.html?highlight=always_return_data#always-return-data
Hope this helps