I'm trying to figure out why my routes have stopped working. I recently upgraded to Ember JS RC 3 (from RC2) and after going through the changelog, I can't figure out why my routes stopped working. Maybe I changed something in trying to fix it; I don't know. But here's what I've got.
Here are my routes.
App.Router.map(function() {
this.route("site", { path: "/" });
this.route("about");
this.resource('posts', { path: '/posts' }, function() {
this.route('new');
this.route('show', { path: '/:post_id' });
this.route('edit', { path: '/:post_id/edit'})
});
this.route("map");
});
Here is my route handler...
App.PostsIndexRoute = Em.Route.extend({
model: function(){
return App.Post.find();
},
setupController: function(controller, model){
controller.set('content', model);
}
});
Here is my model
App.Post = DS.Model.extend({
body: DS.attr('string'),
headline: DS.attr('string'),
creator: DS.attr('string'),
created: DS.attr('date')
});
Here's the JSON being pulled over the network (I see it coming, just not being rendered -- the view is not rendered at all)
[
{
"creatorID": "512808071f7152f9b6000001",
"creator": "Aaron",
"headline": "second entry",
"body": "this is my second entry. ",
"updated": "2013-03-04T20:10:14.566Z",
"created": "2013-03-04T20:10:14.566Z",
"id": "5134ffa6095e930000000001"
},
{
"body": "this is my first entry. ",
"created": "2013-02-28T22:39:32.001Z",
"creator": "Aaron",
"creatorID": "512808071f7152f9b6000001",
"headline": "first entry",
"updated": "2013-03-01T18:13:35.934Z",
"id": "512fdca479d3420000000001"
}
]
Probably also important to note that I do NOT see any JS errors here, as I'm visiting localhost/posts
Thanks for your help!
EDIT: Here is the template I'm using to render the entries (jade based).
div {{content}}
{{#each post in content}}
div(class="post limit-width")
h3(class="headline") {{#linkTo 'posts.show' post}} {{ post.headline }} {{/linkTo}}
p {{{post.body}}}
h6
em Posted by {{post.creator}} on {{post.created}}
{{/each}}
note that the {{content}} tag is being used to determine if there's even an object present; there is, but its length seems to be zero. Which makes me think that no entries are being loaded via Ember Data, but I cannot figure out why.
Related
I'm using RESTAdapter and trying to figure out how to access sideloaded data.
A sample of the payload is:
{
"category": {
"categoryName": "test category",
"id": 6,
"products": [
4419,
502,
3992
]
},
"products": [{
"description": "Whatevs",
"id": 4419,
"name": "Product 1",
"price": 114.95,
"skuid": "S21046"
}, {
"description": "Whatevs",
"id": 502,
"name": "Product 2",
"price": 114.95,
"skuid": "SOLS2594"
}, {
"description": "Whatevs",
"id": 3992,
"name": "Product 3",
"price": 114.95,
"skuid": "S21015"
}]
}
I can see 'category' and 'product' data models (and data) in the ember inspector, so I know they are being loaded.
I can even access the products in the template model.products. BUT I can't access model.products in the route's setupController. The error I get is:
TypeError: Cannot read property '_relationships' of undefined
This is really perplexing me! My route model hook is:
model(params) {
return this.get('store').queryRecord('category', {
id: params.id
})
}
The setupController hook (that causes the error) is:
setupController(controller, model) {
controller.set('results', model.products);
}
The 'category' model:
export default DS.Model.extend({
products: hasMany('product'),
categoryName: attr('string')
});
The 'product' model:
export default DS.Model.extend({
name: attr('string'),
skuid: attr('string'),
price: attr('number'),
description: attr('string')
});
My template (which works, if I remove the 'setupController' hook from the route):
{{#each model.products as |product|}}
{{product.name}} {{product.skuid}}<br />
{{/each}}
I'd like to be able to access model.products from the route's setupController so I can call it something else. Any help appreciated.
Relationship returns Promises. so to get the result you need to use then. but accessing it in template will work because template is by default promise aware.
setupController(controller, model) {
//controller.set('results', model.products);
model.get('products').then((result) => {
controller.set('results',result);
});
}
Please give read on relationships as promises guide.
I have a list of posts, with a nested summary and full route.:
App.Router.map(function() {
this.resource('post', {path: ':post_id'}, function() {
this.route('summary', {path: '/'});
this.route('full');
});
});
The summary route is at path: /, so when I {{#link-to 'post' somePost}}, it arrives in post.summary.
When I change the model, i.e. route to someOtherPost, I would like to stay in the current leaf route (either summary or full).
How do I do this? I tried willTransition, but I'm not sure how to check if the model changed:
Here's a JSBin with what I have so far: http://emberjs.jsbin.com/benot/2/edit?js,output
This is a great use case for a dynamic link-to.
link-to Code
App.ApplicationController = Em.ArrayController.extend({
postLink: 'post'
});
Template
{{#each item in controller}}
<li>{{#link-to postLink item}}{{item.title}}{{/link-to}}</li>
{{/each}}
You can send an action from each child route, and it will go up the router (http://emberjs.com/guides/templates/actions/) until caught. At the parent route you can change the dynamic value of the link-to and bam, you're good to go.
Route Code
App.PostSummaryRoute = Em.Route.extend({
actions:{
didTransition: function(){
this.send('swapLink', 'post.summary');
}
}
});
App.PostFullRoute = Em.Route.extend({
actions:{
didTransition: function(){
this.send('swapLink', 'post.full');
}
}
});
App.ApplicationRoute = Ember.Route.extend({
model: function() {
return [
App.Post.create({id: '1', title: 'Foo', body: 'Lorem'}),
App.Post.create({id: '2', title: 'Bar', body: 'Ipsum'})
];
},
actions: {
swapLink: function(newLink){
console.log('swapLink ' + newLink);
this.controller.set('postLink', newLink);
}
}
});
http://emberjs.jsbin.com/dekokafu/1/edit
I'm trying to get a nested route to make a request for additional data, update the record, and then render the view. See below:
// models
var attr = DS.attr,
hasMany = DS.hasMany,
belongsTo = DS.belongsTo
App.List = DS.Model.extend({
title: attr('string'),
links: hasMany('link')
})
App.Link = DS.Model.extend({
list: belongsTo('list'),
subtitle: attr('string'),
})
// JSON for index route
{
"list": [
{
"id": 532,
"title": "first list"
},
{
"id": 991,
"title": "second list"
},
{
"id": 382,
"title": "third list"
}
]
}
// JSON for list route - /user/532
{
"list":
{
"id": 532,
"title": "list numero uno",
"links" : [1, 2]
},
"link": [
{
"id": 1,
"subtitle": "this is a subtitle of the firsto listo!"
},
{
"id": 2,
"subtitle": "this is a subtitle of a second part in the list"
}
]
}
// routing
this.resource('user', function(){
this.route('list', {path: ':id'})
})
App.UserRoute = Ember.Route.extend({
model: function(){
return this.store.find('list')
}
})
App.UserListRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('list', params.id)
}
})
I want the index route to display a basic list with just the {{title}}, and clicking on one links it to UserListRoute which then makes another ajax call to update the record with the additional link data. I've tried adding:
afterModel: function(modal){
model.reload()
}
to the UserListRoute but it initially uses the index route model, and then it reloads with the new data. I'm trying to avoid this, and make it send an ajax request immediately and then render the content - so I don't want it to depend on the parent model/data.
create a different record type, and extend from the original, or just use a completely different model.
App.BasicList = DS.Model.extend({
foo: DS.attr()
});
App.FullList = App.BasicList.extend({
//foo
bar: DS.attr()
});
App.UserListRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('fullList', params.id)
}
})
I tried with kingpin2k's answer, and it worked on a page refresh but navigating from the user index to the nested still caused it to use the parent model. I figured out why it wasn't used the correct model. My links on the user index template were:
{{#link-to 'user.list' this}} {{title}} {{/link-to}}
So clicking on link correctly redirects me to /users/:id, but it passes on the data of the item selected. To remedy this I did:
{{#link-to `user.list` id}} {{title}} {{/link-to}}
So by changing this to id, when it transitions to the route, it uses the appropriate model specified in the route.
Using the default instructions in the README.md file for a freshly generated Ember-CLI 0.0.20 app, I'm getting a 404 error. I'd love to be able to use the API Stub for offline development.
FWIW, I realize this is a duplicate of How do I setup the api-stub in an ember-cli app?, but the answer on that one isn't working for me, and hasn't been marked as accepted by the asker.
Here's what api-stub/README.md says to do:
API Stub
========
The stub allows you to implement express routes to fake API calls.
Simply add API routes in the routes.js file. The benefit of an API
stub is that you can use the REST adapter from the get go. It's a
way to use fixtures without having to use the fixture adapter.
As development progresses, the API stub becomes a functioning spec
for the real backend. Once you have a separate development API
server running, then switch from the stub to the proxy pass through.
To configure which API method to use edit **package.json**.
* Set the **APIMethod** to 'stub' to use these express stub routes.
* Set the method to 'proxy' and define the **proxyURL** to pass all API requests to the proxy URL.
Default Example
----------------
1. Create the following models:
app/models/post.js
```
var attr = DS.attr,
hasMany = DS.hasMany,
belongsTo = DS.belongsTo;
var Post = DS.Model.extend({
title: attr(),
comments: hasMany('comment'),
user: attr(),
});
export default Post;
```
app/models/comment.js
```
var attr = DS.attr,
hasMany = DS.hasMany,
belongsTo = DS.belongsTo;
var Comment = DS.Model.extend({
body: attr()
});
export default Comment;
```
2. Setup the REST adapter for the application:
app/adapters/application.js
```
var ApplicationAdapter = DS.RESTAdapter.extend({
namespace: 'api'
});
export default ApplicationAdapter;
```
3. Tell the Index router to query for a post:
app/routes/index.js
```
var IndexRoute = Ember.Route.extend({
model: function() {
return this.store.find('post', 1);
}
});
export default IndexRoute;
```
4. Expose the model properties in the index.hbs template
app/templates/index.hbs
```
<h2>{{title}}</h2>
<p>{{body}}</p>
<section class="comments">
<ul>
{{#each comment in comments}}
<li>
<div>{{comment.body}}</div>
</li>
{{/each}}
</ul>
</section>
```
When Ember Data queries the store for the post, it will make an API call to
http://localhost:8000/api/posts/1, to which the express server will respond with
some mock data:
```
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": ["1", "2"],
"user" : "dhh"
},
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
```
api-stub/routes.js:
/* global module */
module.exports = function(server) {
// Create an API namespace, so that the root does not
// have to be repeated for each end point.
server.namespace('/api', function() {
// Return fixture data for '/api/posts/:id'
server.get('/posts/:id', function(req, res) {
var post = {
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": ["1", "2"],
"user" : "dhh"
},
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
};
res.send(post);
});
});
};
app/adapters/application.js:
var ApplicationAdapter = DS.RESTAdapter.extend({
namespace: 'api'
});
export default ApplicationAdapter;
app/models/post.js:
var attr = DS.attr,
hasMany = DS.hasMany,
belongsTo = DS.belongsTo;
var Post = DS.Model.extend({
title: attr(),
comments: hasMany('comment'),
user: attr(),
});
export default Post;
app/models/comment.js:
var attr = DS.attr,
hasMany = DS.hasMany,
belongsTo = DS.belongsTo;
var Comment = DS.Model.extend({
body: attr()
});
export default Comment;
app/routes/index.js:
var IndexRoute = Ember.Route.extend({
model: function() {
return this.store.find('post', 1);
}
});
export default IndexRoute;
app/router.js:
var Router = Ember.Router.extend(); // ensure we don't share routes between all Router instances
Router.map(function() {
this.route('index', {path: '/'});
this.route('component-test');
this.route('helper-test');
// this.resource('posts', function() {
// this.route('new');
// });
});
export default Router;
app/templates/index.hbs:
<h2>{{title}}</h2>
<p>{{body}}</p>
<section class="comments">
<ul>
{{#each comment in comments}}
<li>
<div>{{comment.body}}</div>
</li>
{{/each}}
</ul>
</section>
package.json:
...
"name": "cli2test",
"APIMethod": "stub",
"version": "0.0.0",
"private": true,
"directories": {
"doc": "doc",
"test": "test"
...
The short-term answer on this, from Stefan Penner via Twitter:
#caretpi API stub does not work in cli. We hope to have it integrated soon though— Stefan Penner (#stefanpenner) April 1, 2014
There's an issue open on GitHub: https://github.com/stefanpenner/ember-cli/issues/153
Maybe I'm overlooking something, but I from can't figure out how I'm supposed
I have a JSON coming from the server which looks like this
{
"articles": [
{
"user": {
"name": "user",
"username": "user",
"_id": "52755cba74a1fbe54a000002"
},
"_id": "5275698c53da846e70000001",
"__v": 0,
"content": "content",
"title": "title",
"created": "2013-11-02T21:07:24.554Z"
}
]
}
In the template, I'm accessing content and created fine, but when I try to get user.name, nothing comes out:
{{#each article in model}}
<span>{{ article.title }}</span>
<span>by {{ article.user.name }}</span>
<span>{{ article.created }}</span>
{{/each}}
I noticed that in the model, whatever I don't define, won't appear in the template, so it looks like this:
title: DS.attr('string'),
content: DS.attr('string'),
created: DS.attr('date')
But when I try to add:
user: {
name: DS.attr('string')
}
To match the nested json, I get an error.
Is ember not able to handle nested json? If it is, then how?
Thanks.
This might be the easiest way to support embedded documents (if you don't want to change your JSON):
App.ArticleSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
user: {embedded: 'always'}
}
})
See: http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html. I haven't tested it though!
As mentioned there are heavy changes to embedded records since Ember Data 1.0 beta 1 and there is no more support for it. If you need embedded records you could have a look at ember-data-extensions project: https://github.com/pixelhandler/ember-data-extensions It provides support for embedded record by an EmbeddedAdapter and EmbeddedRecordMixins.
A simple implementation example:
App.ApplicationAdapter = DS.EmbeddedAdapter.extend({});
App.ApplicationSerializer = DS.EmbeddedSerializer.extend();
App.Article = DS.Model.extend({
user: DS.belongsTo('user'),
content: DS.attr('string'),
title: DS.attr('string'),
created: DS.attr('date')
});
App.User = DS.Model.extend({
name: DS.attr('string'),
username: DS.attr('string'),
articles: DS.hasMany('article')
})
App.ArticleSerializer = App.ApplicationSerializer.extend({
attrs: {
user: {embedded: 'always'}
}
});
But you should be aware that there is no support for embedded records only on load yet.
According to the transition guide; Ember data doesn't support embedded records yet.
https://github.com/emberjs/data/blob/master/TRANSITION.md#embedded-records
There is an example of how to implement it yourself. Another option is to use ember-model, it supports embedded associations. I am sorry I don't have an example.