Ember.js: How to use computed property as a route - javascript

I'm pretty new to Ember.js and am building an app to pick up some Ember chops. I wanted to use a computed property in one of my models as a route but it seems something isn't working correctly. I'm using FIXTURES by the way.
What I'm trying to achieve is /peeps/john-smith instead of /peeps/1
I've got my model setup like this:
App.Peep = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
slug: function(){
this.get('firstName').toLowerCase() + '-' + this.get('lastName').toLowerCase();
}.property('firstName', 'lastName')
});
My router setup is like this:
App.Router.map(function(){
this.resource('peep', { path: '/peeps/:peep_slug'});
});
App.PeepRoute = Ember.Route.extend({
model: function(params){
return this.store.find('peep', params.peep_slug);
},
serialize: function(model){
return { peep_slug: model.get('slug') };
}
});
When I navigate to /peeps/john-smith in the browser, I get this warning in my console You made a request for a peep with id john-smith.
Is there something I'm missing?

By default it searches by id param, so you could either change the adapter to make it search by slug or try to add id as Ember.computed.alias('slug').

Related

ember js params is exists

So I need to do so that clicking on the store would stop the page with the goods of this store. When passing the store's id through the link URL changes but in the product's route model(params) the params is empty
Model name (product?)
import DS from 'ember-data';
import { empty } from '#ember/object/computed';
export default DS.Model.extend({
name: DS.attr('string'),
quantity: DS.attr('string'),
price: DS.attr('string'),
shops: DS.belongsTo('shop', {asynq: true}),
isNotValid: empty('name'),
});
Model name (shop?)
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
address: DS.attr('string'),
phone: DS.attr('string'),
products: DS.hasMany('product',{asynq: true}),
});
Controller name (?)
import Controller from '#ember/controller';
export default Controller.extend({
isNew: false,
actions: {
newProduct() {
this.toggleProperty('isNew');
},
cancelNewProducts() {
this.set('isNew', false);
},
addNewProduct() {
const name = this.get('name');
const quantity = this.get('quantity');
const price = this.get('price');
let shop = this.get('store').peekRecord('shop', );
let product = this.get('store').createRecord('product', { name,quantity,price });
shop.get('products').pushObject(product);
product.save().then( function() {
shop.save();
});
product.save().then( ()=> this.set('isNew',false));
},
},
});
Route name (?)
import Route from '#ember/routing/route';
export default Route.extend({
model(params) {
console.log(params.shop_id);
return this.store.query('product', {shops:params.shop_id});
},
actions: {
deleteProduct(product) {
let confirmation = confirm('Are you sure?');
if (confirmation) {
product.destroyRecord();
}
},
editProducts(product) {
console.log(id)
product.set('isEditing', true);
},
cancelProductsEdit(product) {
product.set('isEditing', false);
product.rollbackAttributes();
},
saveProducts(product) {
if (product.get('isNotValid')) {
return;
}
product.set('isEditing', false);
product.save();
},
},
});
Router
import EmberRouter from '#ember/routing/router';
import config from './config/environment';
const Router = EmberRouter.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('shops', function() {
this.route('new');
this.route('edit', { path: '/:shop_id/edit' });
});
this.route('products', { path: '/:shop_id/products' }); // this should be in the map, right?
}); // ?
export default Router;
My problem is that I can not make a request to the server and get the goods only from the store with the available id.But when I click on any store displays all the goods. AND i can't access params(shop_id) from shops in my controller,
I just did a pretty invasive reformatting of your program. Take note of the router. Looks like there are some mistakes in there. Also, you don't provide an id to 'peek' with. In your controller. We also don't know how those files are connected or what their names are. You should edit on top of my formatting to help clarify. {async: true} is spelled with a q in your program.
As far as your question... I'll try and reword it. The word 'store' is confusing... because of the data 'store' that we are used to talking about. I think you mean that you have a 'shop' resource and that you want to 'click' on the shop... (likely a component in an each loop) and then you say you want to 'stop' the page with the goods(products) - so... maybe you mean 'stock' or 'show' the products for that shop. This could be in the component (if only a few) - or you could shoot over to a 'detail' page for the shop - that displayed all of the products for that shop. Because you mention params and ID, I think you mean to go the detail route.
This is my best guess at your question: "I have resources for 'shop' and 'product.' I'm building a UI where shops are listed. I would like to make the shops clickable and when clicked, transition to the shop detail page - where I can list all associated products. My link-to helper(not shown here) takes in a shop ID - but the transition is not successful and the params isn't recognized. What am I doing wrong?"
For this question, you could likely create a more simplified version in an ember-twiddle to get to the bottom of things. We don't really need most of those actions to get to the source of the confusion.
It's admitedly hard to show these things / when you have a server - or a mirage server or whatever your setup is. Here's an example of the routing I would suggest - with some basic dummy data - in an embertwiddle. The data isn't real ember objects / but see the link-to and the shop detail route for what you'd likely use. Good luck!
Other notes:
ember-data uses an attribute called isNew for records - so, you may want to think of a different name for what you're doing /

Dynamic segment value

Just getting started with Ember and have a question about the ember way to handle a common pattern.
I have a have the following router.js:
export default Router.map(function() {
this.resource('posts', function(){
this.route('post', { path: "/:title" });
this.route('new');
});
});
I'm wondering how to use the value of the post title as the dynamic segment so that post urls show up as /posts/my-post-title-here
I'm confused as to which model this is being looked up on or if there is an "ember way" to handle this common patter (besides using the posts_id for the dynamic segment).
All my posts are defined in routes/posts.js, so I thought I simply needed to lookup the values in this route inside of my routes/post.js route, like this:
export default Ember.Route.extend({
model: function(params) {
var posts = this.modelFor('posts')
return posts.findBy('title', params.title);
}
});
I'm seeing the /posts/:title route in my Ember inspector, but in the browser, the links are all undefined ( /posts/undefined ).
{{#each model as |post|}}
{{#link-to "posts.post" model }}
<li>{{post.title}}</li>
{{/link-to}}
{{/each}}
I'd love any advice about the proper way to handle this situation or explanations about how Ember looks up values for nested routes.
You need to setup a serializer on your routes/post.js, like this:
// routes/post.js
export default Ember.Route.extend({
model: function(params) {
var posts = this.modelFor('posts')
return posts.findBy('title', params.title);
},
serialize: function(model) {
return { post_slug: model.get('title') };
}
});
See Dynamic Segments

Reloading ember data from server

I'm trying to reload store data from the server after transitioning to a page.
The transition i'm referring in this case, is from an index page, to a specific page by id.
here is my code:
App.Board = DS.Model.extend({
title: DS.attr('string'),
boardItems: DS.hasMany('BoardItem'),
});
App.BoardItem = DS.Model.extend({
title: DS.attr('string'),
board: DS.belongsTo('Board')
});
App.BoardIndexRoute = Ember.Route.extend({
model: function() {
return {
title: 'Boards List',
boardItems: this.store.find('board')
}
}
});
App.BoardShowRoute = Ember.Route.extend({
model: function(params) {
// this.store.reloadRecord('BoardItem'); - tried this, didn't work :(
var boardData = this.store.findById('board', params.board_id);
return boardData;
}
});
what happens is:
Index - loads a list of boards, with empty boardItems array (I don't want to load all of the data on the index)
Then clicking a link to a specific board, transitions to it, but the data is empty and no requests made to the server.
I tried various ways of reloading it, but all fails...
here is the debug info if it might help:
DEBUG: Ember : 1.5.1 ember.js:3521
DEBUG: Ember Data : 1.0.0-beta.7.f87cba88 ember.js:3521
DEBUG: Handlebars : 1.1.2 ember.js:3521
DEBUG: jQuery : 2.1.0
Thanks!
Finding Records: If you provide a number or string as the second argument to store.find(), Ember Data will attempt to retrieve a record of that with that ID. This will return a promise that fulfills with the requested record:
App.BoardShowRoute = Ember.Route.extend({
model: function(params) {
// Providing both the model name, and board identifier
// Make sure the parameter exists.
// console.debug('My board identifier is', params.board_id');
return this.store.find('board', params.board_id); // => GET /boards/:board_id
}
});

EmberJS: How to load multiple models on the same route?

While I am not new to web development, I am quite new to to client-side MVC frameworks. I did some research and decided to give it a go with EmberJS. I went through the TodoMVC guide and it made sense to me...
I have setup a very basic app; index route, two models and one template. I have a server-side php script running that returns some db rows.
One thing that is very confusing me is how to load multiple models on the same route. I have read some information about using a setupController but I am still unclear. In my template I have two tables that I am trying to load with unrelated db rows. In a more traditional web app I would have just issued to sql statements and looped over them to fill the rows. I am having difficulty translating this concept to EmberJS.
How do I load multiple models of unrelated data on the same route?
I am using the latest Ember and Ember Data libs.
Update
although the first answer gives a method for handling it, the second answer explains when it's appropriate and the different methods for when it isn't appropriate.
BEWARE:
You want to be careful about whether or not returning multiple models in your model hook is appropriate. Ask yourself this simple question:
Does my route load dynamic data based on the url using a slug :id? i.e.
this.resource('foo', {path: ':id'});
If you answered yes
Do not attempt to load multiple models from the model hook in that route!!! The reason lies in the way Ember handles linking to routes. If you provide a model when linking to that route ({{link-to 'foo' model}}, transitionTo('foo', model)) it will skip the model hook and use the supplied model. This is probably problematic since you expected multiple models, but only one model would be delivered. Here's an alternative:
Do it in setupController/afterModel
App.IndexRoute = Ember.Route.extend({
model: function(params) {
return $.getJSON('/books/' + params.id);
},
setupController: function(controller, model){
this._super(controller,model);
controller.set('model2', {bird:'is the word'});
}
});
Example: http://emberjs.jsbin.com/cibujahuju/1/edit
If you need it to block the transition (like the model hook does) return a promise from the afterModel hook. You will need to manually keep track of the results from that hook and hook them up to your controller.
App.IndexRoute = Ember.Route.extend({
model: function(params) {
return $.getJSON('/books/' + params.id);
},
afterModel: function(){
var self = this;
return $.getJSON('/authors').then(function(result){
self.set('authors', result);
});
},
setupController: function(controller, model){
this._super(controller,model);
controller.set('authors', this.get('authors'));
}
});
Example: http://emberjs.jsbin.com/diqotehomu/1/edit
If you answered no
Go ahead, let's return multiple models from the route's model hook:
App.IndexRoute = Ember.Route.extend({
model: function() {
return {
model1: ['red', 'yellow', 'blue'],
model2: ['green', 'purple', 'white']
};
}
});
Example: http://emberjs.jsbin.com/tuvozuwa/1/edit
If it's something that needs to be waited on (such as a call to the server, some sort of promise)
App.IndexRoute = Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
model1: promise1,
model2: promise2
});
}
});
Example: http://emberjs.jsbin.com/xucepamezu/1/edit
In the case of Ember Data
App.IndexRoute = Ember.Route.extend({
var store = this.store;
model: function() {
return Ember.RSVP.hash({
cats: store.find('cat'),
dogs: store.find('dog')
});
}
});
Example: http://emberjs.jsbin.com/pekohijaku/1/edit
If one is a promise, and the other isn't, it's all good, RSVP will gladly just use that value
App.IndexRoute = Ember.Route.extend({
var store = this.store;
model: function() {
return Ember.RSVP.hash({
cats: store.find('cat'),
dogs: ['pluto', 'mickey']
});
}
});
Example: http://emberjs.jsbin.com/coxexubuwi/1/edit
Mix and match and have fun!
App.IndexRoute = Ember.Route.extend({
var store = this.store;
model: function() {
return Ember.RSVP.hash({
cats: store.find('cat'),
dogs: Ember.RSVP.Promise.cast(['pluto', 'mickey']),
weather: $.getJSON('weather')
});
},
setupController: function(controller, model){
this._super(controller, model);
controller.set('favoritePuppy', model.dogs[0]);
}
});
Example: http://emberjs.jsbin.com/joraruxuca/1/edit
NOTE: for Ember 3.16+ apps, here is the same code, but with updated syntax / patterns: https://stackoverflow.com/a/62500918/356849
The below is for Ember < 3.16, even though the code would work as 3.16+ as fully backwards compatible, but it's not always fun to write older code.
You can use the Ember.RSVP.hash to load several models:
app/routes/index.js
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return Ember.RSVP.hash({
people: this.store.findAll('person'),
companies: this.store.findAll('company')
});
},
setupController(controller, model) {
this._super(...arguments);
Ember.set(controller, 'people', model.people);
Ember.set(controller, 'companies', model.companies);
}
});
And in your template you can refer to people and companies to get the loaded data:
app/templates/index.js
<h2>People:</h2>
<ul>
{{#each people as |person|}}
<li>{{person.name}}</li>
{{/each}}
</ul>
<h2>Companies:</h2>
<ul>
{{#each companies as |company|}}
<li>{{company.name}}</li>
{{/each}}
</ul>
This is a Twiddle with this sample: https://ember-twiddle.com/c88ce3440ab6201b8d58
Taking the accepted answer, and updating it for Ember 3.16+
app/routes/index.js
import Route from '#ember/routing/route';
import { inject as service } from '#ember/service';
export default class IndexRoute extends Route {
#service store;
async model() {
let [people, companies] = await Promise.all([
this.store.findAll('person'),
this.store.findAll('company'),
]);
return { people, companies };
}
}
Note, it's recommended to not use setupController to setup aliases, as it obfuscates where data is coming from and how it flows from route to template.
So in your template, you can do:
<h2>People:</h2>
<ul>
{{#each #model.people as |person|}}
<li>{{person.name}}</li>
{{/each}}
</ul>
<h2>Companies:</h2>
<ul>
{{#each #model.companies as |company|}}
<li>{{company.name}}</li>
{{/each}}
</ul>
I use something like the answer that Marcio provided but it looks something like this:
var products = Ember.$.ajax({
url: api + 'companies/' + id +'/products',
dataType: 'jsonp',
type: 'POST'
}).then(function(data) {
return data;
});
var clients = Ember.$.ajax({
url: api + 'clients',
dataType: 'jsonp',
type: 'POST'
}).then(function(data) {
return data;
});
var updates = Ember.$.ajax({
url: api + 'companies/' + id + '/updates',
dataType: 'jsonp',
type: 'POST'
}).then(function(data) {
return data;
});
var promises = {
products: products,
clients: clients,
updates: updates
};
return Ember.RSVP.hash(promises).then(function(data) {
return data;
});
If you use Ember Data, it gets even simpler for unrelated models:
import Ember from 'ember';
import DS from 'ember-data';
export default Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller,model);
var model2 = DS.PromiseArray.create({
promise: this.store.find('model2')
});
model2.then(function() {
controller.set('model2', model2)
});
}
});
If you only want to retrieve an object's property for model2, use DS.PromiseObject instead of DS.PromiseArray:
import Ember from 'ember';
import DS from 'ember-data';
export default Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller,model);
var model2 = DS.PromiseObject.create({
promise: this.store.find('model2')
});
model2.then(function() {
controller.set('model2', model2.get('value'))
});
}
});
The latest version of JSON-API as implemented in Ember Data v1.13 supports bundling of different resources in the same request very well, if you don't mind modifying your API endpoints.
In my case, I have a session endpoint. The session relates to a user record, and the user record relates to various models that I always want loaded at all times. It's pretty nice for it all to come in with the one request.
One caveat per the spec is that all of the entities you return should be linked somehow to the primary entity being received. I believe that ember-data will only traverse the explicit relationships when normalizing the JSON.
For other cases, I'm now electing to defer loading of additional models until the page is already loaded, i.e. for separate panels of data or whatever, so at least the page is rendered as quickly as possible. Doing this there's some loss/change with the "automatic" error loading state to be considered.

Ember Data - TypeError: Object has no method 'eachRelationship'

So, I'm trying to build routes in my Ember application dynamically with data from an API endpoint, /categories, with Ember Data. In order to do this, I'm adding a didLoad method to my model, which is called by the controller and set to a property of that controller. I map the route to my router, and all that works fine. The real trouble starts when I try to set up a controller with a content property set by data from the server retrieved by findQuery.
This is the error:
TypeError {} "Object /categories/548/feeds has no method 'eachRelationship'"
This is the code:
window.categoryRoutes = [];
App.Categories = DS.Model.extend({
CATEGORYAFFINITY: DS.attr('boolean'),
CATEGORYID: DS.attr('number'),
CATEGORYNAME: DS.attr('string'),
CATEGORYLINK: function () {
var safeUrl = urlsafe(this.get('CATEGORYNAME'));
categoryRoutes.push(safeUrl);
return safeUrl;
}.property('CATEGORYNAME'),
didLoad: function () {
var categoryLink = this.get('CATEGORYLINK');
var categoryId = this.get('CATEGORYID');
App.Router.map(function () {
this.resource(categoryLink, function () {
// some routes
});
});
App[Ember.String.classify(categoryLink) + 'Route'] = Ember.Route.extend({
setupController: function(controller, model) {
// source of error
this.controllerFor(categoryLink).set(
'content',
this.store.findQuery('/categories/' + categoryId + '/feeds', {
appid: 'abc123def456',
lat: 39.75,
long: -105
})
);
}
});
}
});
Any 'halp' is appreciated!
Also, if I'm doing this completely wrong, and there's a more Ember-like way to do this, I'd like to know.
I figured this out. I got this error because I was passing in a string instead of a real 'type' from the App.Helpers object to an extract method in some custom RESTAdapter code I had overridden.
The solution is to pass in the corresponding model helper in App.Helpers using my custom type name.
Something like this in the overridden RESTAdapter.serializer.extractMany method:
var reference = this.extractRecordRepresentation(loader, App.Helpers[root], objects[i]);

Categories