Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have hasOne relation with embedded always relation

EmberJS has removed hasOne in the earlier revision. Whats the way to create such a nested object relation where I want to have hasOne

Removal of hasOne has been done in favor of belongsTo, can anyone share a thought on how to write {embedded : always} relation between nested JSON.

like image 732
sudhanshu Avatar asked Feb 04 '13 11:02

sudhanshu


2 Answers

I know that this question is old and answered, but since it is one of the top search results for "ember hasone" i wanted to share my findings on the subject. I've read the link in the first answer but the example is kinda outdated.

The "embedded" flag is obsolete, "DS.RESTAdapter.map" is not a function and the "DS.hasOne" method deprecated.

The current 1.0.0-beta.2 solution for emulating the "hasOne relationship" is simply using "DS.belongsTo". They are not very different and you just need to add the hasOne foreignKeys to your result-set just like you would with belongsTo.

Source: https://github.com/emberjs/data/commit/a466741a36731c5d382df33461268024627325ef

Here's an example server response from a complex model.

{"users": [{
  "id": 1,
  "name": "John Doe",
  "profile": 27,        // merged hasone
  "image": 3,           // merged hasone
  "account_id": 64      // an actual belongsTo
}]}

And then as model

App.User = DS.Model.extend({
   name: DS.attr('string'),
   profile: DS.belongsTo('profile'),
   image: DS.belongsTo('image'),
   account_id: DS.belongsTo('account')
});

Hope this helps anyone looking for info on how to model a hasOne

like image 154
m3nt0r Avatar answered Oct 22 '22 22:10

m3nt0r


You have to set the mapping on the adapter, please see this answer for a working example.

like image 1
Adrien Coquio Avatar answered Oct 22 '22 23:10

Adrien Coquio