Search code examples
ruby-on-railsember.jsurl-routingbrowser-historyrails-routing

Rails 4 Ember Routing with History API


I have a problem trying to get the history API to work properly with ember in my rails app.

This all works perfectly with the # URLs.

In Rails I have a controller with an index action that renders my app. The whole page is the ember app, so it just loads the JS, stylesheets etc.

I have two Rails routes...

root 'home#index'
get 'posts', :to => 'home#index'

So I can render my rails app with either www.example.com OR www.example.com/posts

In Ember I specify the history api in the router...

App.Router.reopen({
    rootURL: '/',
    location: 'history'
});

I then have a single Ember route set-up...

Delib.Router.map(function() {
    this.resource('posts');
});

I have templates for the Index and Posts routes.

When I enter the root URL I get the Index template displayed.

When I enter the posts url e.g. /posts it still renders the Index template.

I added the logging info and it seems to recognize the posts route and then transition into the Index route, see below...

DEBUG: ------------------------------- ember.js?body=1:382
DEBUG: Ember.VERSION : 1.0.0-rc.8 ember.js?body=1:382
DEBUG: Handlebars.VERSION : 1.0.0 ember.js?body=1:382
DEBUG: jQuery.VERSION : 1.10.2 ember.js?body=1:382
DEBUG: ------------------------------- ember.js?body=1:382
generated -> route:posts.index Object {fullName: "route:posts.index"} ember.js?body=1:382
generated -> controller:application Object {fullName: "controller:application"} ember.js?body=1:382
Rendering application with default view <(subclass of Ember.View):ember387> Object {fullName: "view:application"} ember.js?body=1:382
generated -> controller:index Object {fullName: "controller:index"} ember.js?body=1:382
Rendering index with default view <Ember._MetamorphView:ember403> Object {fullName: "view:index"} ember.js?body=1:382
Transitioned into 'index' 

I get a single HTTP Request for this, so it definitely isn't a HTTP redirect.

Interestingly, it has registered the move from /posts to / in the history API - so my back button is enabled and if I click back it correctly transitions to the /posts route and my posts Template is rendered. Again, this all works when I use the standard # URLs.

Anyone got any idea what I am doing wrong? Or is this somehow expected behaviour or is it an ember bug?

Thanks in advance! Post if you need more info.


Solution

  • Seems I have fixed it. After building a standalone ember app (without Rails) to confirm that ember was working correctly I returned to my app and magically it worked.

    It seems this was down to Rails not reloading a controller/model or something similar. Unfortunately I now cannot repeat the problem - so am leaving this answer in case somebody else hits this problem they can perhaps add more info or at least solve it by restarting their app.