psr7-demo
psr7-demo copied to clipboard
Automatically populate other side of relationship
Given these two models:
attr = FP.attr
hasMany = FP.hasMany
hasOne = FP.hasOne
App.Advisor = FP.Model.extend
name: attr "string"
tickets: hasMany "tickets", embedded: false
App.Ticket = FP.Model.extend
advisor: hasOne "advisor", embedded: false
I expected that the following would not only create a ticket but populate the "tickets" reference of the existing, associated advisor model with a new entry, but it doesn't:
App.AdvisorIndexRoute = Ember.Route.extend
afterModel: (advisor) ->
ticket = @store.createRecord "ticket",
advisor: advisor
ticket.save()
In other words, starting with:
{
"advisors": {
"G5FF": {
"name": "Smith"
}
}
}
I expected saving the ticket to produce:
{
"advisors": {
"G5FF": {
"name": "Smith",
"tickets": {
"-JJWYEO-S7K2HTDyeQvV": true
}
}
},
"tickets": {
"-JJWYEO-S7K2HTDyeQvV": {
"advisor": "G5FF"
}
}
}
But instead, I only get:
{
"advisors": {
"G5FF": {
"name": "Smith"
}
},
"tickets": {
"-JJWYEO-S7K2HTDyeQvV": {
"advisor": "G5FF"
}
}
}
It does the right thing to get the advisor's id to populate the ticket, but it doesn't complete the picture, so to speak. Is this expected behavior, such that I'm supposed to manually take steps to add the other side of the relationship? Or am I doing something wrong?
+1 came here to say this.
I tried it the other way, with the same outcome:
ticket = @store.createRecord "ticket",
advisor: advisor
advisor.get("tickets").addObject ticket
advisor.save()
The result is:
{
"advisors": {
"G5FF": {
"name": "Smith",
"tickets": {
"-JJWYEO-S7K2HTDyeQvV": true
}
}
}
}
Nothing in the root tickets collection...
Walking through the code confirms that there's nothing that would give the desired behavior, so it's not a bug, but simply correct, albeit limited, behavior. Fireplace does all the necessary heavy-lifting to properly determine relationship references (as when it correctly knew that the advisor key was "G5FF" in the first example I gave) but saving to Firebase is just a simple dump of the model being saved after the JSON is filled out. So, for now, the only thing to do is call save on all models involved.