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
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.