ember-data does not support embedded objects [duplicate] - ember.js

This question already has an answer here:
Ember-data embedded records current state?
(1 answer)
Closed 8 years ago.
i'm working with ember data rev-11 and django tastypie. Looks like now ember-data does not support embeded resources but support sideloads (django tastypie does not support it). What is the best solution?
Thanks

This is not valid for Ember Data 1.0 beta+, see duplicate answer
Ember-data still supports embedded. You just need the right configuration. Here how you can do it:
DS.RESTAdapter.map('App.Foo',{
bar:{
embedded:'always'
}
})
App.Foo = DS.Model.extend({
bar: DS.belongsTo(App.Bar,{embedded:'always'}),
});
Available values for embedded are: always and load.
load: The child records are embedded when loading, but should be saved
as standalone records. In order for this to work, the child records
must have an ID.
always: The child records are embedded when loading, and are saved
embedded in the same record. This, of course, affects the dirtiness of
the records (if the child record changes, the adapter will mark the
parent record as dirty).
Similar settings apply for HasMany relationship, see this reply for more details

Related

Ember Data: Pushing the data to the store will not replace the changedAttributes of the record?

I am using Ember Data and I have a model say my-model. I am having a realtime notification server to update my application if there is any change for a record. When I am editing an attribute of my-model from UI, the model has some changedAttributes and when the real time notification comes, I am fetching the record from the server and pushing it to the store using store.push(store.normalize('my-model', data)).
Now, In the store the model still has my changedAttributes and it is not replaced. So I believe, the Ember Store will not replace the entire record and will replace only the clean attributes of the record when I do a store.push. I just want to confirm the behaviour. Can someone confirm if my understanding about this is right?
For something like this I think your best bet is to add a test to ember data itself to cover the desired behavior. This would be much more reliable than anything you might hear on Stackoverflow.
I've written a small Ember Twiddle to test that behavior: https://ember-twiddle.com/a8eb87a1c7e5019214320d81af05aca5?openFiles=templates.application.hbs%2C As it shows ember-data does not reset dirty attributes if the record is pushed again into the store - at least not for the tested version 3.4.2, which is a little bit outdated.
I wasn't able to find any tests in ember-data repository that covers your use case but I'm also not that familiar with Ember Data's source code. So you might want to open an issue there or ask on Ember Community Discord or Ember Discussion Forum if this is expected behavior.
To be honest I guess there should be a straight-forward solution to your problem as realtime notification (e.g. through WebSocket) is a common use case.

How to get count of model records without loading them all

I have a problem. I have a news model in my background application and my Emberjs app. And there are a lot of news posts can be stored, so I have to divide loading them to some pages or whatever. The problem is - I need to always get a full count of not readed news posts. What is the best way to implement such behaviour in my Ember application?
If you are using Ember Data, I would take a look at Handling Metadata.
The default JSON deserializer looks for a property named meta which could contain something like "totalUnreadPosts": 10
You could get to the metadata with var metaData = store.metaDataFor('newsPost'); which would allow you to get a count without having to load every post.

Ember-Model: How to establish a hasMany or belongsTo relationship by using a "foreign key"?

Summary
I have a bit of a problem using Ember-Model, trying to establish a unique relationship between two models.
Based on current responses that I have received here on S.O., Ember Forums, and #emberjs. I am beginning to believe that there is no built-in solution for this problem, and I am reformatting my question to specify what is needed.
Details
I am populating a template currently with a full set of debtor information. All the information comes from multiple calls to the server.
The first bit is the basic Debtor info. This part is easy because I can use the model hook and a dynamic segment to retrieve it.
My server returns a JSON for a Debtor... Here's the short version:
{
"debtor" = {
"debtor_id": 1003,
"debtor_name": Steve,
//... more JSON
"debtor_contact_id": 1345
}
}
The dynamic segment for Debtor is filled with the value of the debtor_id, but also notice this debtor has a debtor_contact_id. Every Debtor record retrieved from the server has a unique debtor_contact_id. On the database, this value is a "foreign key" that will tell which contact table belongs to which debtor table.
There is no way to predict which contact info relates to which debtor without this key/value pair.
I currently have "Contacts" belongsTo "Debtor", but that is not enough to do the job.
When it is time to fill the "Contacts" model. Ember-Model needs to know to build the value from debtor_contact_id into the ajax URL as a query parameter in order to GET the correct API.
I am still learning all of this stuff and so far I have not been able to fully follow any tutorials because my use case has an extra step needed somewhere.
This is the expected behavior I am hoping to see:
Model hook will work as expected to pull the specific debtor and put it into a "debtor" model (this part is currently working just fine)
Somehow "debtor_contact_id" is read from the payload
that value is added as part of a server query to find a separate API
the resulting contact info will be pulled into a "contact" model
hopefully a hasMany/belongsTo relationship can be established after both corresponding models are returned.
all this needs to be done in one promise before entering my template
You will also find the question at: discuss.emberjs.com if that is more appropriate place to discuss.
I can elaborate more if this does not make sense... thanks!
Assuming you are using ember-data, alongside the attributes of your model you need to add:
debtor_contact: DS.belongsTo('name_of_the_other_model')
This then provides you a promise which will resolve to the other model on demand. It won't resolve straight away, but bound variables in templates will update as it is resolved. The other API call will be made for you if things are set up properly.
http://emberjs.com/api/data/classes/DS.html#method_belongsTo
The answer I gave here might also be helpful if you need to force resolving the relationship for some reason: Ember Unbound & Belongsto

Mixing ember-data and non ember-data models

In my API and on my server I have a model hierarchy like this:
WorkoutPlan->workouts->exercises
I can successfully load that structure with DS.hasMany relationships.
However, my client side view breaks up the plan into weeks so it would be nice to have a client side model structure of
WorkoutPlan->weeks->workouts->exercises
Is it possible to do this if weeks isn't an ember-data model?
If not, should I just transform my JSON so that I can has a hasMany on a Week model (workouts have a week column I could use as a quasi id for the week model).
Or would it be best to keep the current model structure and just somehow filter workouts somehow by week.
Your ember model doesn't have to mimic your server model. There're usually good reasons to de-normalize, minimize the amount of data and simplify the model. For example, the server deals with multiple users, your ember app is likely just concerned with one.
I see two options here. I don't know enough about your model to suggested what's the best.
Add WeekPlan as a model. You could change the serialization logic in your server (if you have an app specific API) or change this during the serialization client side (if this change won't make sense for other API consumers).
Add a filter in your workout router. Also you could have an ArrayController with weeks that simply aggregates the weeks from the workouts in a workout plan.
In general I would lead towards 1, but as I said I don't know enough about your model to make a strong case for either.
Update. Expand on 2
There're two parts to this. The first one is the WeekPlanRoute. That might look something like the following. It's basically responsible to create an array of Weeks and uses that to pass it to pass the workouts to a WorkoutRoute/Controller
App.WeekPlaneRoute = Ember.Route.extend({
model: function(){
// assuming we already have a WorkoutPlan
return workoutPlan.workouts.mapBy('week');
},
);
Then you can navigate to the workouts by using a link-to that passes the week as a parameter:
{{#each}}
{{#link-to 'workouts.index' this}}{{/link-to}}
{{/each}}
In your WorkoutRoute you will filter using that parameter:
Todos.WorkoutRoute = Ember.Route.extend({
model: function(params){
// assuming we already have a WorkoutPlan
return workout.filterBy(params.weekNumber);
}
);
You will also have to change your route to add that dynamic segment for the weekNumber (it has to match that param used above).
this.resource('workouts', {path: '/workouts/:weekNumber'});

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()?