Skip to content

How to order records by impressionist_count.

Sergio Tapia Gutierrez edited this page Apr 5, 2014 · 1 revision

In a usual setup, you can access the impressionist count for a record using something like:

@product.impressionist_count

In some cases, you want to create a list of 'most viewed' records, or order them by view count.

First, create a new column in your Product model, called impressions_count.

class AddCounterCacheToProduct < ActiveRecord::Migration
  def change
    add_column :products, :impressions_count, :integer, default: 0
  end
end

Then, you need to add the :counter_cache option to your model.

class Product < ActiveRecord::Base
  is_impressionable counter_cache: true
end

With this in place, your impressions_count column in the Product model will automatically increment.

Finally, this in place you can easily order the records by view count:

@most_viewed = Product.order('impressions_count DESC').take(10)

Happy programming!