Jeremy Gillick
Jeremy Gillick

Reputation: 2700

Emberjs: How to get a single object from find() (findAll)

I'm building a e-commerce site and have the shopping cart as a model accessible by the web service /api/cart/. Using the RESTAdapter, I'd like to simply call App.Cart.find() and always return 1 object, not an array. The cart doesn't have an ID, so calling App.Cart.find(1) would be wrong -- plus that would create a bad web service call: /api/cart/1.

Do I need to extend the RESTAdapter or Model to make find() on App.Cart always return an object instead of a list?

Upvotes: 4

Views: 1765

Answers (1)

Bram
Bram

Reputation: 765

App.Cart.find().then(function (result) {
  return result.get('firstObject'); 
});

return a promise to the first object and then do something with that if thats done. Note you can use this in the model method of route to becaulse ember handles promises nicely.

I used in that model. Works perfect in the last ember version.

model: function(params) {
    return App.Cart.find({slug: params.slug}).then(function (obj) {
        return obj.get('firstObject');
    });
}

Upvotes: 6

Related Questions