Access Record by ID from Model inside Component


#1

When I pass a model with multiple records associated with it into component like so

{{high-chart data=model}}

I can extend the component with functions that include a model.map, for example, which allows me to access each record in the model.

Similarly, I can pass a particular record in a model to a component like so

{{#each model as |data|}} {{area-chart data=data}} {{/each}}

And in extending the component, I can then access the fields for each record in the model with

this.get(‘data’).get(‘title’)

or

this.get(‘data’).get(‘subtitle’)

etc.

But what I would like to be able to do is pass a whole model to a component and then pick a particular record out of the model by id from within the component.

Is there a way to do that? I can’t figure out what method to call on the model to get a particular record – or the syntax to use in the template to do the same.

Help!


#2

I think you can use findBy


#3

Unfortunately not as simple as that.

What I see in the inspector when I pass the model into the component with all of its records is an Ember Data DSAdapterPopulatedRecordArray object, which is an extension of the Ember Data RecordArray class, which in turn is an extension of the Ember ArrayProxy class.

The ArrayProxy class includes a get(‘content’) method, which gives me the array it wraps. But that array is an array of internal models

[ ember$data$lib$system$model$internal$model$$InternalModel, ember$data$lib$system$model$internal$model$$InternalModel, ember$data$lib$system$model$internal$model$$InternalModel]

…and the documentation for the Ember Data InternalModel class tells me that it

should never be exposed to application code. At the boundaries of the system, in places like find, push, etc. we convert between Models and InternalModels.

So how do I convert the InternalModels into regular models inside the component?


#4

Hmm, maybe just inject store to your component, and find the data you need from it. :smile:


#5

I’ve used findBy in the past and it works well. I treat DSAdapterPopulatedRecordArray and RecordArray as if they are arrays. Someone correct me if I am wrong, but because it is difficult to extend arrays in JavaScript, I think Ember created the ArrayProxy class as a way to mimic arrays. That’s why it has pretty much all the methods that native JavaScript arrays have. And those same methods are enabled on Array.prototype when Ember’s prototype extensions are enabled (which is the default).

If findBy doesn’t work, can you provide an example why?


#6

Okay so findBy was the answer, but I was tripped up by the fact that the second argument (the value in the key, value pair that findBy requires) had to be passed in as a string. Since it’s a number, I was just passing it in as a number, which findBy apparently doesn’t like.

Thanks for your help!