0

A common pattern for a user's settings page would be for it to live at /settings.

In my Rails app, I'm accomplishing this on the API side by mapping get 'settings' to Settings#show and looking for the current_user's settings.

But on the Ember side, I'm stumped. There's no ID to use for the GET request, so I can't use the typical pattern of this.store.find('setting', params.id) within my route.

What's the "Ember way" of handling this sort of use case?

Josh Smith
  • 14,674
  • 18
  • 72
  • 118

1 Answers1

1

This has been discussed here: http://discuss.emberjs.com/t/fetching-single-records/529/3


The issue with loading a single record not based on an ID, is that you need to get back a DS.Model object as a promise. If you get back a record that's already in the client's memory you would now have two different objects representing the same record (type and id combination). Take this example:

var user123 = App.User.find(123);
var currentUser = App.findByUrl('/users/current'); //This is an imaginary method, i.e. Ember Data don't support it
notEqual(user123, currentUser, "The user objects can't be the same cause we don't know what the current user is yet");

Now we get this response from the server:

{
    "user": {
        "id": 123,
        "name": "Mufasa"
    }
}

Now currentUser and user123 both have id 123, but they are essentially different objects = very bad. This is why this approach wouldn't work.

Instead you will want to load a record array of users, listen for it to load, and then take the firstObject from the loaded records. Like this:

var users = App.User.find({ is_current: true });
users.one('didLoad', function() {
    App.set('currentUser', users.get('firstObject');
});


$.ajax({
    type: 'GET',
    url: '/users/current',
    success: function(payload) {
        var store = this.store;
        var userReference = store.load(App.User, payload.user);
        App.set('currentUser', store.recordForReference(userReference));
    }.bind(this)
});
jasonmit
  • 1,268
  • 8
  • 8