1
votes

I'm building a chat based application which allows users to view message history, send new messages and select from recent users. The recent user list is being sorted by a recent_rating attribute which is the date of the last sent/received message related to that user. The recent_rating is not an attribute in the database, but a method being declared within the user model. The users are being ordered properly when I load the page for the first time with the following set up in my code:

Serializer:

class UserSerializer < ActiveModel::Serializer
    attributes :id, :email, :name, :recent_rating
end

Rails model:

    def recent_rating
        Message.where('recipient_id = :user_id OR sender_id = :user_id', user_id: id).last.try(:created_at)
    end

Ember Controller:

App.ChatsController = Ember.ArrayController.extend(
{
    sortProperties: ['recent_rating'],
    sortAscending: false,

    ....
});

Ember model:

App.User = DS.Model.extend(
{
  name: DS.attr('string'),
  email: DS.attr('string'),
  recent_rating: DS.attr('string'),
});

However, when I send a new message, I need to update the recent_rating attribute in the local ember-data storage for the related user record. This would in turn update the list ordering for recent users.

How can I update the attribute for a record in Ember-Data and avoid the API POST request? As recent_rating doesn't exist as an attribute in the database on the API side

Thanks

1
A model shouldn't persist to the server until save is called on it, how are you updating a record? - Jakeii

1 Answers

0
votes

There is a technical way to do what you're asking (store#push), but I think the design is a bit off here.

Here's how I would model this. A user hasMany messages, and a message has a createdAt property. Then ordering the users by latest message becomes a matter of a few simple computed properties:

App.Message = DS.Model.extend({
  user: DS.belongsTo('user'),
  createdAt: DS.attr('date')
});

App.User = DS.Model.extend({
  messages: DS.hasMany('message'),
  name: DS.attr('string'),
  email: DS.attr('string'),

  messagesSorting: ['createdAt:desc']
  orderedMessages: Ember.computed.sort('messages', 'messagesSorting'),
  latestMessage: Ember.computed.alias('orderedMessages.firstObject')
});

Now in your controller/component (whatever's displaying the users), you can create a new computed property to sort the users:

App.SomeController = Ember.Controller.extend({
  usersSorting: ['latestMessage:desc'],
  sortedUsers: Ember.computed.sort('model', 'usersSorting')
});

and use that property in your template.


P.S. you should start using Ember CLI if possible :)