3

I’m building an Ember.js application, using Ember data, ActiveModel serializer, and Ember Simple Auth Devise, connecting to a Rails API and trying to understand how I could build a route that loads a single resource, in this case for a "my account" page for the current user.

From the Rails perspective I don't need an ID, but on the Ember side I’m not sure how to accomplish this. My workaround has been to supply a placeholder ID, which Rails ignores. Is there a better way to accomplish this?

Ember.js:

MyAccountRoute = Ember.Route.extend(model: -> @store.find 'account', '1')

Rails:

def show
  @item = @current_user.account
end
Gordon Isnor
  • 2,065
  • 1
  • 19
  • 32

4 Answers4

4

Ember Data has a very specific implementation when you use find

find called with the type only expects a collection of that type, this maps to findAll

find called with the type and a primitive type (non object) will expect a single object response of that type, this maps to findById

find called with the type and an object will expect a collection (possibly filtered server side by the parameters sent in), this maps to findByQuery

So using Ember Data there is no way to do this, unless you want to hack it into one of your other implementations, or use ajax to call back and then sideload the store. I prefer using the pattern you're using, I do this.store.find('user', 'me'); And then ignore the parameter.

Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
0

The way I am tackling this is by returning an array/collection of records that only contains a single record.

Then in Ember you can access this single result using .get('firstObject') like this

export default Ember.Route.extend({
  model: function() {
    return this.store.find('user').then(function (users) {
      return users.get('firstObject');
   });
 }
});

This feels more like an Ember way of doing things and also avoids an issue you may notice if you use the Ember developer tools plugin; That the returned data actually creates a duplicate record - you end up with an empty record with an id of me or 1 and a complete record with the ID of the single record returned.

An alternative approach is continue using me or 1 and to set or modify the ID of the returned record to match. In this case you would return a single object and not an array/collection.

Binarytales
  • 9,468
  • 9
  • 32
  • 38
0

Ember data has queryRecord method.

This method makes a request for one record, where the id is not known beforehand

http://emberjs.com/api/data/classes/DS.Store.html#method_queryRecord

Anton K
  • 557
  • 5
  • 9
0

I combined the two answers and used queryRecord with a parameter ignored by server.

return this.store.queryRecord('user_settings', {id: 'me'});

thanks Binarytales and antulik

bcavileer
  • 51
  • 5