klye_g
klye_g

Reputation: 1242

EmberJS Search Store

I am attempting to write a small action that searches the data store, which already has data loaded into it by the way. I would like to be able to search by a string, i.e. a firstname.

Here is an example of the code I have so far. this.get() is grabbing the value from the search form and I know it's getting the correct value from the input field.

actions: {
    search: function() {
        return this.store.all('person', { firstName: this.get('firstName') });
    },
}

And here is the model:

App.Person = DS.Model.extend({
    firstName:      attr('string'),
    lastName:       attr('string'),
    email:          attr('string'),
});

When I run this action, it simply returns ALL of the records in the DS.

Also, separate question but does Ember do LIKE statements? Let's say the first name is Stanley and I enter in Stan. Would it retrieve Stanley or does it look for exact matches only?

I cannot find anything via google or the documentation, and I may be phrasing the question the wrong way.

Thanks in advance.

Upvotes: 0

Views: 94

Answers (3)

Carl
Carl

Reputation: 760

To search in an already loaded store you can use peekAll the get all records and then find by using the findBy method. This won't trigger an request.

return this.store.peekAll('person').findBy('firstName', this.get('firstName'));

Upvotes: 0

Kingpin2k
Kingpin2k

Reputation: 47367

Use filter

var liveCollection = this.store.filter('foo', function(record){
  // if the bar property is baz include it in the collection
  return record.get('bar')=== 'baz'; 
});

So for your case it'd be

search: function() {
    var fn = this.get('firstName');
    return this.store.filter('person', function(record){
       return record.get('firstName') === fn; 
    });
},

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

Upvotes: 1

Jason
Jason

Reputation: 26

Try using the find instead of all function

return this.store.find('person', { firstName: this.get('firstName') });

Upvotes: 0

Related Questions