Ember has a steep learning curve because a) it isn't stable yet, b) there’re so many outdated examples on the web that can lead you astray. Ember-Data, a twin-brother is a trickier beast to boot. Being under heavy development, things have been changing so fast that today’s snippet is not longer relevant. On the one hand it’s pretty tricky to learn Ember, on the other, yup, it’s all about cutting-edge – you know the drill!
Today’s problem made my head spin, but after asking here and there, with the help of awesome guys on Stackoverflow and Ember IRC channel, I have finally made it, yay!
So let’s get down to the nitty-gritty. I’d like to show you how to use hasMany relation in fixtures in Ember-Data revision 12.
First you have to define the Fixture Adapter for a model. Remember that you can mix fixtures and real data (REST adapter) in order to speed up development.
The examples (very simplified) below are written in Coffee Script.
App.Store = DS.Store.extend revision: 12 adapter: 'DS.RESTAdapter' #default adapter # server doesn’t return real data yet App.Store.registerAdapter 'App.Post', DS.FixtureAdapter App.Store.registerAdapter 'App.Comment', DS.FixtureAdapter
Let’s define our models:
App.Post = DS.Model.extend comments: DS.hasMany 'App.Comment' title: DS.attr 'string' content: DS.attr 'string' App.Comment = DS.Model.extend post: DS.belongsTo 'App.Post' title: DS.attr 'string' content: DS.attr 'string'
And our fixture data:
App.Post.FIXTURES = [ id: 1 title: 'Big brother is watching you!' content: 'Smith! You’re being watched!' comments: [1, 2] , id: 2 title: 'Novus ordo seclorum' content: 'How come brown cow?' comments: [3, 4, 5] ] App.Comment.FIXTURES = [ id: 1 title: 'I can't believe it!' content: 'world is soo beautiful on the TV!' , id: 2 title: 'Hey dude, we’re in the 21st century!' content: 'in your face!' , id: 3 title: 'Hey, I think I saw it somewhere!' content: 'it must be good' , id: 4 title: 'WTF?!' content: 'another conspiracy theorist ha ha' , id: 5 title: 'We’re doomed!' content: 'politicians must do sth about it!' ]
The tricky part is how to make make it work. Actually it boils down to this part:
comments: [1, 2]
making you feel good. :)
I don’t think it is documented well, at least I couldn’t find it. In contrast to JSON returned by the server, you don’t have to define _ids suffix.
I was told that Ember fixtures are great because of their simplicity, and when you’re done, switching to real data is a walk in the park.
Hope you find it useful. Oh, and of course you can access it in handlebars templates as you would with real data, that is via a controller.