How to Make Ember.js Behave with Grails Controller Names?

ember-data, ember.js, grails

Solution

Good question, self!

Ember.js, and its auto-AJAX-in-browser-data-store ninjitsu expect the URL to look a certain way, and the JSON to look a certain way. Due to the way that each tool works, it's easier to make conforming changes to both sides of the equation!

What Grails Provides

For a Domain class `MyCoolDomainClass` with a controller `MyCoolDomainClassController`, Grails wants to provide the URL `/app/myCoolDomainClass`. If you set up the controller to contain something along the lines of:

def index() { render MyCoolDomainClass.list() as JSON }

You'll get a response that looks like:

`[{ id: 1, name: "Bob"}, {id: 2, name: "Sally"}]`

What Ember Wants

In Ember.js, you might create a Model with the same properties. By leveraging `ember-data`, you can easily hook up the Data Store in the browser with your backend. Unfortunately, what Ember.js wants is different. It expects the the url `/my_cool_domain_class` to provide the data:

`{ mycooldomainclass: [ { id: 1, name: "Bob"}, {id: 2, name "Sally"}] }`

Reconciling

UPDATE: I've created a `ember-data-grails` repo on Github which takes care of all of these modifications for you, and demonstrates how to make a controller that plays along nicely!

Problem

Grails is pretty powerful, and lets you turn your Domain objects into JSON with a single statement (`object as JSON`). Unfortunately, this is not sufficient to interact with Ember.js for a few reasons. How can I make Grails play nicely with Ember.js?

Original source