I've got an ember-data model that has an id as well as a server-generated custom slug attribute (which is prefixed with the id if that matters).
I'd like to use the slug instead of the id in all public routres. For that purpose, I have changed the router:
App.Router.map ->
#resource 'strategies', path: '/strategies', ->
#resource 'strategy', path: ':strategy_slug'
and overwrote the serialize method of the respective route:
App.StrategyRoute = Ember.Route.extend()
serialize: (model) ->
{
strategy_slug: model.get('slug')
}
Unfortunately, this does not seem to work when using transitionToRoute from a controller to transition to, e.g., /strategies/123-test:
App.ExampleController = Ember.ObjectController.extend()
[...]
actions:
showDetails: ->
#transitionToRoute("/strategies/#{#get('slug')}")
false
(where #get('slug') returns '123-test')
All output I get in the console after invoking the showDetails action is:
Transitioned into 'strategies.index'
Ember does seem to recognize the slug-based route.
Ember: 1.5.0-beta.2+pre.3ce8f9ac
Ember Data: 1.0.0-beta.6
Is there anything I may have missed?
Edit:
The following variant works and is feasible in this case, but I have another use-case where I have only access to the URL.
App.ExampleController = Ember.ObjectController.extend()
[...]
actions:
showDetails: ->
#transitionToRoute('strategy', #get('content'))
false
I eventually figured out how to solve this. The key is to add a model method to the router, which knows how to turn a slug into a model:
App.StrategyRoute = Ember.Route.extend()
model: (params, transition) ->
App.store.getById('strategy', parseInt(params.strategy_slug))
serialize: (model) ->
{
strategy_slug: model.get('slug')
}
Related
I'm building an office reception app in Ember. When a person arrives at the office, they pop open the app and are taken through a three step wizard:
Choose a reason for visiting
Choose the person you've come to see
Confirm
The app also allows an administrator to view all of the visits and to view an individual visit.
I have Visit and Person models I've hooked up to a server using Ember Data. Here's what my routes look like:
App.Router.map () ->
#resource 'visits', ->
#resource 'visit', { path: '/:visit_id' }
#resource 'new', ->
#route 'welcome'
#route 'directory'
#route 'thanks'
This allows me to create a new Visit model in the VisitsNewRoute and use it in the welcome, directory and thanks views.
This works. However, it feels wrong to have a new resource, especially since it's conceivable I'll want at least one more new route in my application.
Is there a better way to do this?
I think that you can change the new resource to newVisit like this:
App.Router.map () ->
#resource 'visits', ->
#resource 'visit', { path: '/:visit_id' }
#resource 'newVisit', ->
#route 'welcome'
#route 'directory'
#route 'thanks'
Now you will have a NewVisitRoute where you can create a new Visit model to use in each of the child routes.
And you will be able to make a transition to this routes with the route names: newVisit.welcome, newVisit.directory and newVisit.thanks. You can use this route names in a link-to helper link this:
{{link-to "Welcome", "newVisit.welcome"}}
The recommended practice is to use a create/new route under the resource type, so new under visits, then `transitionTo('visit.welcome', newRecord). (I'm saying all of this with the assumption that welcome, directory, and thanks aren't part of the new record creation).
App.Router.map () ->
#resource 'visits', ->
#route 'new'
#resource 'visit', { path: '/:visit_id' }
#route 'welcome'
#route 'directory'
#route 'thanks'
Ember doesn't always name routes the way you want when dealing with routes nested more than one level. I would name your 'new' route as follows:
#resource 'visits.new', path: 'new', ->
There are a number of approaches you can use to structuring your routes depending on how you assign model ids and whether or not you are using localStorage to preserve user edits until they are persisted to the server.
I have my route pattern as follows:
App.Router.map () ->
#resource 'visits', ->
#route 'new'
#route 'crud', path: ':visit_id'
My 'new' routes create a new resource in the routes model callback which in my models auto-generates a v4 UUID. The new route then performs a transitionTo the crud route in the afterModel callback. In effect the 'visits.new' route acts as a trampoline and allows you to easily use {{link-to 'visits.new'}} from templates/menus etc.
The above approach allows you to to have a single crud route and crud controller that can handle all the show/create/update/delete actions for the model. The models isNew property can be used within your templates to handle any differences between create and update.
I also use localStorage so that newly created (but not yet persisted) models survive a browser refresh, the UUIDs really come in handy for both this and for persisting complex model graphs.
The above router pattern occurs quite a lot in my app so I have defined some base Route classes and a route class builder but the general pattern is as follows:
If using UUIDs:
App.VisitsNewRoute = Em.Route.extend
model: (params, transition)->
App.Visit.create(params)
afterModel: (model,transition) ->
#transitionTo 'visits.crud', model
App.VisitsCrudRoute = Em.Route.extend
model: (params,transition) ->
App.Visit.find(params['visit_id'])
If not using UUID's then the routes are different. I did something like this before I moved to UUIDs, it treats model id 'new' as a special case:
App.Router.map () ->
#resource 'visits', ->
#route 'crud', path: ':visit_id'
App.VisitsCrudRoute = App.Route.extend
model: (params, transition) ->
visit_id = params['visit_id']
if visit_id == 'new' then App.Visit.create() else App.Visit.find(visit_id)
serialize: (model, params) ->
return if params.length < 1 or !model
segment = {}
segment[params[0]] = if model.isNew() then 'new' else model.get('id')
segment
For your specific case of managing the wizard step state I would consider using Ember Query Params, which allow you specify the current step in a parameter at the controller level
Query params example:
App.VisitsCrudController = Em.ObjectController.extend
queryParams: ['step'],
step: 'welcome'
Link to next step in the view:
{{#link-to 'visits.crud' (query-params step="directory")}}Next{{/link-to}}
You may also want to define some computed properties for the next and previous steps, and some boolean properties such as isWelcome, isDirectory for your view logic.
I have a nested edit route:
#resource 'dashboard.communities.community', path: ':community_id', ->
#route 'edit'
In my route, I try to retrieve the model with modelFor:
CivicSourcing.DashboardCommunitiesCommunityEditRoute = Ember.Route.extend
model: (params, queryParams, transition) ->
#modelFor('community')
But this returns undefined. The parent route is successfully retrieving the community, though. Any idea what might be going on?
You're resource name is dashboard.communities.community not community
#modelFor('dashboard.communities.community')
Here's a similar example for colors.cool
http://emberjs.jsbin.com/OxIDiVU/442/edit
When the route /facades get visited I want to redirect to the first facade. This generally works, but as the list from the server is not sorted, my code doesn't redirect to the "first" facade. I know how to sort in the controller, but how can I sort in the router/ model by any property?
App.FacadesRoute = Ember.Route.extend
model: ->
#get("store").find("facade")
redirect: ->
facade = #modelFor("facades").get("firstObject")
#transitionTo("facades.show", facade)
redirect is deprecated, the recommendation is afterModel, and findProperty is super easy for finding a model in a collection based on some property in the model or if you don't know exactly you can use sortBy.
App.FacadesRoute = Ember.Route.extend
model: ->
#get("store").find("facade")
afterModel: (model, transition) ->
facade = model.findProperty("someproperty", "value on some property");
// or
facade = model.sortBy("someproperty").get('firstObject');
#transitionTo("facades.show", facade)
Ok, I just found a way which works. Not sure if it's the best, but I think this could be useful to others too:
App.FacadesRoute = Ember.Route.extend
model: ->
#get("store").find("facade")
redirect: ->
sortedFacades = Ember.ArrayProxy.createWithMixins Ember.SortableMixin,
sortProperties: ["id"]
content: #modelFor("facades")
facade = sortedFacades.get("firstObject")
#transitionTo("facades.show", facade)
Given the following routes:
App.Router.map ->
#resource 'locations', path: '/:location_id', ->
#route 'events', path: '/events/:date'
App.LocationsEventsRoute = Ember.Route.extend
model: (params) ->
location_id = #modelFor('locations').get('id')
console.log location_id
Accessing "/#/gothenburg-se/events/2013-09-03", location_id returns null. This worked before v1.0. What changed and how do I fix this?
This is likely due to changes in Ember Data for 1.0.beta.1. You might want to check out the transition document.
https://github.com/emberjs/data/blob/master/TRANSITION.md
I think something like this would work for your route:
App.LocationsEventsRoute = Ember.Route.extend({
model : function(params){
// find returns a promise
var locProm = this.store.find('location',params.location_id);
// once the promise has resolved you can log the id
locProm.then(function(loc){
console.log( loc.get('id') );
});
// return the promise immediately and let Ember resolve it
return locProm;
}
});
I just want to be able to display a campaign model's properties in the templates rendered in the my resource template's outlet.
My router looks like this:
App.Router.map (match)->
#resource 'campaigns', ->
#resource 'campaign',
path: ':campaign_id', ->
#route 'chat',
path: '/chat'
I set up 3 templates for my campaign resource:
campaign
campaign.index
campaign.chat
I am not sure how I am supposed to get acces to the model identified by the dynamic segment in my url. I was able to set it up successfully in my campaign route like so:
App.CampaignRoute = Ember.Route.extend
model: (params) -> App.Campaign.find(params.campaign_id)
This doesn't seem to work for the index and chat routes.
I was thinking something like {{someProperty}} or {{campaign.someProperty}} would work by default here.
Why does the context change and how do I get it?
My routes and templates are rendering fine, minus the context I want.
Setting the model this way in my campaign.index and campaign.chat routes made all the difference:
App.CampaignIndexRoute = Ember.Route.extend
model: ->
#modelFor('campaign')
App.CampaignChatRoute = Ember.Route.extend
model: ->
#modelFor('campaign')