Search code examples
arraysember.jscomponentsember-data

Ember can't iterate over model with array property


I have a model, values.js:

import DS from 'ember-data';

export default DS.Model.extend({
    values: [
        { name: "Quality", isChecked: DS.attr('bool') },
        { name: "Inspiration", isChecked: DS.attr('bool') },
        { name: "Creativity", isChecked: DS.attr('bool') },
        { name: "Commitment", isChecked: DS.attr('bool') },
        { name: "Honour", isChecked: DS.attr('bool') }
    ]
});

And in the route passport-values.js I am creating a values model:

import Ember from 'ember';

export default Ember.Route.extend({
    model () {
        return this.store.createRecord('values');
    }
});

I have a component, passport-basic.hbs:

<h2>{{title}}</h2>
<p>{{content}}</p>
<form>
    <fieldset class="checkboxes">
        {{#each model as |value index|}}
            <label>{{input type="checkbox" onchange=(action "change") checked=value.isChecked name="value.name"}}{{value.name}}</label>
        {{/each}}
    </fieldset>
</form>

Which I am using from my template, passport-values.hbs, and passing my model with:

{{passport-basic title="" content="" model=values}}

In the component I am trying to iterate over all the values within the array in the model to display a label with the name and checkbox that represents whether the isChecked option is true/false for each value. I have experimented with ideas from a lot of other sources, but i can't seem to make this work.

Thanks for the help, I'm still very new to Ember.js and I'm wondering if there's something I'm missing?


Solution

  • You can follow the examples in The Guides for Defining Models and Finding Records in order to iterate over a collection in the way you've described, and take advantage of Ember's built in ways to persist records.

    Your value model should look like this:

    import DS from 'ember-data';
    
    export default DS.Model.extend({
      quality: DS.attr('boolean'),
      inspiration: DS.attr('boolean'),
      honor: DS.attr('boolean'),
      creativity: DS.attr('boolean'),
      commitment: DS.attr('boolean')
    });
    

    Then in your route, do

    import Ember from 'ember';
    
    export default Ember.Route.extend({
      model() {
        return this.get('store').findAll('value');
      }
    });
    

    Your model hook will return a collection of values that you can pass to a component just how you described:

    {{passport-basic title="" content="" model=values}}
    

    and you can use the value attributes in your templates like this:

    {{#each model as |value|}}
      <p>{{value.honor}}</p>
    {{/each}}