Constant Meiring
Constant Meiring

Reputation: 3325

Cannot get Rails REST API to work with Ember.js

I'm busy following this Ember.js tutorial, but I'm trying to implement it using the Ember 2.0 way of doing things (modules, using Ember CLI and the ember-cli-rails gem). It's rather difficult since none of the Ember guides follow these conventions.

As per the tutorial, I'm using Rails as a JSON API and it looks like everything works like it should in terms of serving the proper JSON responses. Problem is, I can't get my leads model to work.

I'm getting a TypeError: Cannot read property 'typeKey' of undefined error from ember.debug.js. I'm also getting a undefined is not a function error from ember.adapter.js

My project looks as follows:

app/store.js

  import DS from 'ember-data';

  export default DS.RESTAdapter.reopen({
    url: 'https://localhost:3000',
    namespace: 'api/1'
  });

app/router.js

import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

Router.map(function() {
    this.resource('leads', { path: '/' });
});

export default Router;

app/adapters/application.js

import DS from "ember-data";

var ApplicationAdapter = DS.ActiveModelAdapter.extend({
    host: 'http://localhost:3000',
    namespace: 'api/v1'
});

export default ApplicationAdapter;

app/models/lead.js

import DS from 'ember-data';

export default DS.Model.extend({
  firstName: DS.attr('string'),
  lastName: DS.attr('string'),
  email: DS.attr('string'),
  phone: DS.attr('string'),
  status: DS.attr('string', { defaultValue: 'new' }),
  notes: DS.attr('string'),
});

app/routes/leads.js

import Ember from 'ember';

export default Ember.Route.extend({
    model: function() { return this.store.find('lead') }
});

I don't see any HTTP requests being made to Rails, so I assume that it breaks even before trying to use the API. Can anybody please point out what I'm doing wrong here?

Upvotes: 2

Views: 373

Answers (1)

Constant Meiring
Constant Meiring

Reputation: 3325

Looks like the issue was store.js, which shouldn't be used here. Not sure why, but removing it causes everything to work as it should.

UPDATE: So, upon learning more of how Ember works, I now know the issue was not the file, but that Rails returns the wrong type of json back. The Ember REST adapter expects json keys to use an underscore, eg. first_name, while Rails returns it in camel case, eg. firstName.

To use Ember with Rails, you need to use the ActiveModel adapter. The newest version of ActiveModelSerialisers(AMS) supports JSON API.

Upvotes: 1

Related Questions