Ember.js find single element without ID

I'm building an Ember.js app using Ember data, an ActiveModel serializer and Ember Simple Auth Devise, connecting to the Rails API and trying to figure out how I can build a route that loads one resource, in this case the My Account Page for the current user.

From a Rails perspective, I don't need an ID, but on the Ember side I'm not sure how to do this. My workaround was to provide a placeholder id that Rails ignores. Is there a better way to do this?

ember.js:

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

      

Rails:

def show
  @item = @current_user.account
end

      

+3


source to share


4 answers


The way I solve this is returning an array / collection of records that only contains one 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');
   });
 }
});

      



It's more like a smart way of doing things, and it also avoids the problem you might notice if you're using the Ember developer plugin; The fact that the returned data actually creates a duplicate record - you get an empty record with an ID, me

or 1

and a complete record with an ID of the returned single record.

An alternative approach continues using me

or 1

and to set or change the returned record ID to match. In this case, you should return a single object, not an array / collection.

0


source


Ember Data has a very specific implementation when you use find

find

called with a type only expects a set of that type, it maps to findAll

find

called with a type and a primitive type (not an object) expects a single response from an object of that type, it maps to findById



find

called with a type and the object will expect a collection (maybe filtered server side by the parameters sent to) this matches findByQuery

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

AND then ignore the parameter.

+4


source


Ember data has a method queryRecord

.

This method makes a request for one record where the identifier is not known in advance

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

0


source


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

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

      

thanks Binarytales and antulik

0


source







All Articles