Ember to Ruby on Rails

How does Ember talk to Ruby on Rails?

As you know, at Prospect.io we use Ember.js to handle our frontend and Ruby on Rails for our backend.

In in this section, we are going to see how Ember sends data to the backend.

Sending Requests

ApplicationAdapter

Adapters are used in Ember to format AJAX requests sent to our backend. At Prospect.io, we use a custom ApplicationAdapter that will help us format our requests to match the convention of our backend.

This adapter will, amongst other things:

  • Specify the URL of the backend server

  • Configure headers (CSRF token, Client Type, ...)

  • Build the custom URL for a specific data

We will go deeper into the last point: how does our custom adapter builds the URL for any request, regarding the convention of our backend.

In our case, Rails conventions tells us that we need pluralized snakecase URLs. The role of our adapter will be to format these URLs, based on the data it will send.

As we're interacting with companies in our example, it will take the URL of our backend api/private and add companies at the end of it, resulting in api/private/companies.

Here are a few examples of Model classes and their matching URLs:

Theses URLs will all match their respective endpoints that are configured in our backend.

You don't need to create an adapter for every model classes of the frontend, as there is a default adapter for mostly every entity. In a few cases though, you may need a custom adapter to handle your data.

Custom Adapters

We can implement custom adapters for a specific model if we want to make exceptions to some conventions made by our ApplicationAdapter (i.e: URLs inflections). The custom adapter will be named after its entity: employee-line.js.

For example, we could want to override the pathForType method to specify a custom URL for a record.

Let's take our EmployeeLine ressource. We saw earlier that its URL would be api/private/employee_lines, but we want it to be api/private/employee/lines. To do so, we would create a custom adapter called employee-line.js and implement it like this:

import ApplicationAdapter from 'prospectio/adapters/application';

export default ApplicationAdapter.extend({
  pathForType: function() { return 'employee/lines'; }
});

In this piece of code, we just override the pathForType method defined in our ApplicationAdapter to have a different behaviour for this ressource.

Don't hesitate to check the codebase if you want to see more about our custom adapters.

Last updated