EmberJS custom primary key

EmberJS is a framework for creating ambitious web applications. It follows a convention over configuration software development paradigm.

ID as a primary key

Using ID as a default primary key on database level is an example of convention over configuration paradigm applied, inter alia, in Ruby on Rails framework. It has also some consequences in EmberJS. According to Ember data documentation:

Records without an id property are not considered embedded records, model instances must have an id property to be used with Ember Data.

So as long as you have id column in your database and return it as a part of JSON payload you are safe. However, for variety of reasons (e.g. more efficient database indexes), sometimes it is more reliable to use another column as a primary key. One of the most common example is UUID.

If you use decide to use a custom column as a primary key Ember will start complaining about it. Nonetheless, a solution is straightforward.

Ember serializer and custom primary key

In Ember, or in Ember Data to be precise, serializers are responsible for formatting the data sent to and received from the server. The most popular serializers are JSONSerializer, JSONAPISerializer and RESTSerializer. All of them have primaryKey attribute which can be overwritten:

The primaryKey is used when serializing and deserializing data. Ember Data always uses the id property to store the id of the record. The external source may not always follow this convention. In these cases it is useful to override the primaryKey property to match the primaryKey of your external store.

Example:

// app/serializers/user.js
import ApplicationSerializer from './application';

export default ApplicationSerializer.extend({
  primaryKey: 'uuid',
})

It is worth underlining that value of the primaryKey attribute needs to be defined as it comes from an external store. In my case it was unique_identifier, not uniqueIdentifier.

 

Igor Springer

I build web apps. From time to time I put my thoughts on paper. I hope that some of them will be valuable for you. To teach is to learn twice.