New model to represent existing model with a count

I have a Tag model in my app. In one location I want to display a “top 10” list of tags which will show the tags that are most commonly used (by their many-to-many association with the primary models). This will be a query params interface so I can show the top 10 by various criteria and time ranges.

I can see two ways to implement this.

  1. Add a “count” field to my Tag model which, in most cases will be undefined (or some default value) but when queried at a specific route will be the correct value.

or

  1. Create a new TagCount model that is essentially a one-to-many relationship with Tag with a single “count” field.

Any thoughts on this or alternate implementations?

I can’t think of an alt that’s much easier than 1.

1 Like

So I tried this and it mostly works. Since the counts come from a group_by clause my query (when counting aggregates) looks like:

Tag.select('tag.*, count(tag.id) as count').where(...).group('tags.id')

and my serializer looks like:

class TagSerializer < ActiveModel::Serializer
  attributes :id, :ident, :name, :count

  def count
    object.respond_to?(:count) ? object.count : 1
  end
end

Adding a count: DS.attr('number') attribute to my Ember model and voila it works…

Except, that the where clause changes in different contexts (e.g. counts by month, by week, by day) so that in a template where I want to view the week values and the month values, the second query overrides the count on the model instance. I should have foreseen this. Still looking into a way to work around it.