3

Is it possible to find an individual record based on its property in the views in Ember 1.0.0-rc.5? I've been searching around for days, but I still can't find anything that works.

For example, I would like to be able to do this:

App.Tag.find({name: 'some tag'}) which is supposed to return one record, but instead returns an array.

The name field is unique for all tags, so it should return only one object.

How can this be done?

Thanks

4

2 回答 2

5

Problem solved! For people who might encounter the same problem, I will answer my question here. I ended up using the filter method to select one object. Details here http://emberjs.com/api/classes/Ember.Enumerable.html#method_filter

Code:

...
tagList = App.Tag.find().filter (item, index, enumerable) ->
    return item.get('slug') is "slug title"

tag = tagList.get('firstObject')
...
于 2013-06-07T04:14:42.673 回答
1

When passing a query to a model's find method, you're invoking the findQuery method, which is designed to populate an array.

This is findQuery's definition:

findQuery: function(store, type, query, recordArray) {
    var root = this.rootForType(type),
    adapter = this;

    return this.ajax(this.buildURL(root), "GET", {
      data: query
    }).then(function(json){
      adapter.didFindQuery(store, type, json, recordArray);
    }).then(null, rejectionHandler);
  },

Which then calls didFindQuery upon success, to populate the array which is returned:

didFindQuery: function(store, type, payload, recordArray) {
    var loader = DS.loaderFor(store);

    loader.populateArray = function(data) {
      recordArray.load(data);
    };

    get(this, 'serializer').extractMany(loader, payload, type);
  },

So, assuming my understanding is correct, given that each 'name' in your case is unique, just get the first key of your array:

var tags = App.Tag.find({name: 'some tag'});
var tag = tags[0];
于 2013-06-06T10:53:39.713 回答