Ember 2.7, Rails 5, JSONAPI, Active Model Serializers - counting the number of records in a hasMany relationship

感情迁移 提交于 2019-12-25 04:48:12

问题


This idea started with this question.

2 models:

class Trail < ApplicationRecord
  has_many :notes, dependent: :destroy
end

class Note < ApplicationRecord
  belongs_to :trail
end

2 serializers:

class NotesSerializer < ActiveModel::Serializer
  attributes :id, :note_body

  belongs_to :trail
end

class TrailSerializer < ActiveModel::Serializer

  attributes  :id,
              :name,
              :notes_count

  has_many :notes

  def notes_count
    object.notes.size
  end
end

When calling the route trails/index, this will fire for every Trail, a count query to count the number of 'child' notes for each Trail. Obviously you would have pagination on the /trails/index route, but if your page size is 100 (not unreasonable) this fires 101 queries.

Since I'm doing the full stack, I can easily remove that notes_count from the API completely, and instead, do this in the client (EmberJS):

app/models/trail.js

import DS from 'ember-data';

export default DS.Model.extend({
  <...other attributes here...>
  notes: DS.hasMany('note', { async: true }),

  // the above relationship already exists, but now 
  // I add the below computed property since I 
  // removed it from the API

  notesCount: Ember.computed('notes', function() {
    return `${this.get('notes.length')}`;
  })
});

This is possible because JSONAPI includes the relationship 'notes' so I can just count its length.

My question is:

  1. Is this good? Moving the count to the client seems fine to me, since 'notes' will never be very long, but it does mean the client has to do that length calculation on the index route in the client for each trail. So 100 calculations for a page with 100 trails showing.

  2. Is the better solution to leave this in the API but have an actual count property on the Trail model (ie. stored in the database) that gets updated every time a note is added or deleted for that trail? Obviously the count might be a little 'stale' sometimes, but that's not a big issue.

If you HAD to have this count property in the API would you do (2) or leave it as a calculated attribute in the serializer?

来源:https://stackoverflow.com/questions/39391167/ember-2-7-rails-5-jsonapi-active-model-serializers-counting-the-number-of-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!