How to unwrap first item in hasMany Ember Data model?

I’m working with a relatively complicated domain model that is using asynchronous hasMany relationships. In my user interface, I would like to allow the user to edit the first item in that relationship. However, I’m struggling to unwrap the promise and get to the first item. The each helper is able to handle these relationships, but since I need to deal with the first item, it won’t help in this case. I tried the “with” helper, but it didn’t seem to properly unwrap the object either.

Can anyone suggest the proper way to handle these types of Ember Data relationships?

Thanks, Craig

Well, each helper can yield every index out for you, so you can use that to determine if it is the first one:

{{#each collection as |item index|}}
  {{#if (eq index 0)}}
    {{! do anything with the first item}}
  {{/if}}
{{/each}}

I use ember-truth-helpers in this example, this maybe the simplest way to unwrap first item. But I think it would be better to use CP to exact the first item in advance, so we can get more clean and descriptive template.

BTW, you mentioned with helper before, since an async relationship is a EmberArrayProxy (or similar type I guess), so this may works as well:

{{#with (get collection 'firstObject') as |item|}}

{{/with}}

I never did this before, just an idea that came up suddenly, you can try if it works.

1 Like

nightire - Thanks for the fast response and ideas. I’m happy to say that the first option works, although I really like the look of the second option. However, I’m unsure if the second option is possible prior to 2.0? (we are currently still on the 1.13 branch)

Based on GitHub - jmurphyau/ember-get-helper: Ember Get Helper for HTMLBars, it seems like the get helper is included in Ember 2.0 and that this extension does not work correctly with 1.13. Is there any other way that you can think of while still on top of 1.13 to accomplish the second option?

An associated question… If we wanted to make the leap to 2.0 from 1.13, would we need to fix all deprecations before making the change or is that just a “good idea”? I know that there is a move in 2.0 away from MVC to pure components, but is it fair to assume that our current controller implementations would continue to work for some period of time on the 2.x versions?

Thanks again, Craig