Hey guys,
I need help…again
My project have a model Conversation and a model Message. And I configure Conversation with hasMany Messages and Messages belongsTo Conversation.
That’s ok, but when I route to url http://localhost:4200/conversations I need to list all conversations and when user click in an specific conversation I load the messages belongs to this conversation.
But when I try to access conversation.messages.content this does not works.
{{#each model as |conversation| }}
{{conversation.messages.name}}
{{/each}}
I only can access the attributes of model Conversation but can’t access attributes of Messages. And when I print {{conversation.messages}} I receive this: subclass of Ember.ArrayProxy.
Anyone can help me understand where I’m be so stupid? I search all the documentation and can’t understand.
conversation.messages
is an array, since each conversation has many messages. So it doesn’t make sense to access the name of a list of messages. If you want to get the name of each message, you’ll need an inner loop to iterate through the messages.
{{#each model as |conversation|}}
{{#each conversation.messages as |message|}}
{{message.name}}
{{/each}}
{{/each}}
2 Likes
This make sense. You are right it! I forgot it. But this doesn’t work, I’m have a fake API with ember-cli-mirage with Adapter and Serializer in JSONAPI. In my routes/conversations/index.js I have this:
return this.store.findAll('conversation');
And I also try this:
let conversation = this.store.findAll('conversation');
conversation.get('messages').then((messages) => { return conversation });
But can’t access attributes of messages I’m loosing my mind with this
OK, I found the error.
Like I say, I’m using JSONAPI. So in my serializers/application.js I defined this:
import DS from 'ember-data';
import Ember from 'ember';
export default DS.JSONAPISerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr);
},
keyForRelationship(key, relationship) {
if (relationship === 'belongsTo') {
return `${key}_id`;
}
}
});
So I thought it was working. But not. I change for this:
import DS from 'ember-data';
import JSONAPISerializer from 'ember-data/serializers/json-api';
import Ember from 'ember';
export default JSONAPISerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr);
},
keyForRelationship(key, relationship) {
if (relationship === 'belongsTo') {
return `${key}_id`;
}
},
attrs: {
messages: { serialize: true }
}
});
And now this works. Now I can access the model Messages