0
votes

I'm trying to build a simple chat app using Ember CLI with a rails API backend, using simple-auth-devise. I am very new to Ember. I have the following setup:

  • A conversation model which has_many messages. Each message belongs_to a user.
  • A conversations/show route which loads a conversation and displays all messages

The problem I have is figuring out which messages were written by the current user. I can identify the current user in the route and pass this to the controller, but I'm not sure how to do something in the template which is conditional on this. Here is the code:

Route for conversations/show:

import Ember from 'ember';

export default Ember.Route.extend({

model: function(params) {
  return this.store.find('conversation', params.conversation_id);
},

// Get the current user
setupController: function(controller, model){
  this._super(controller, model);
  var currentUser = this.get('session').get('currentUser');
  controller.set("currentUser", currentUser);
}

});

Then in the template I want to do something like this:

{{#each message in messages}}

    {{message.body}}
    {{#if message.isByCurrentUser }}
        Written by me!
    {{/if}}
{{/each}}

I don't know how or where to define that message.isByCurrentUser method to use the currentUser variable defined in the route.

Many thanks in advance.

1

1 Answers

0
votes

I would recommend you to separate message resource and let it have its own template and controller.

//messages.hbs
{{#each message in messages}}
  {{render "message" message}}
{{/each}}

//message.hbs
{{message.body}}
{{#if isByCurrentUser }}
  Written by me!
{{/if}}

//message controller
import Ember from 'ember';
export default Ember.Controller.extend({
 currentUser: Ember.computed.alias('session.currentUser'),
 isByCurrentUser: function() {
   return this.get('model.creator.id') === this.get('currentUser.id'); 
 }.property('model.creator', 'currentUser') 
});

P.S: I assumed your message model has attribute named creator. change it due to your model

simple-auth injects session into controllers and routes so you don't have to set it explicitly.