Order

To order the results of a report, use the order option. Similar to SQL, this accepts values like 1, 1 asc, or 1 desc to order by the first column ascending or descending. If multiple series are used, you can use 2 desc to order by the second series descending, for example.

You can also order by properties of a dimension. For example, if the first dimension is tags and you want to sort by tag names ascending, you can use dimension1.label asc.


To create the chart above, simply add the following YAML file and call render_report in any view:

YAML

config/reports_kit/reports/order_overview.yml

measure: post
dimensions:
- tags
order: dimension1.label asc

View

app/views/my_controller/my_view.html.haml

= render_report 'order_overview'

Model

app/models/post.rb

class Post < ApplicationRecord
  belongs_to :author
  has_many :post_views, dependent: :destroy
  has_many :posts_tags, dependent: :destroy
  has_many :tags, through: :posts_tags

  include ReportsKit::Model
  reports_kit do
    aggregation :average_time_to_publish, [:average, 'posts.published_at - posts.created_at']
    contextual_filter :for_author, ->(relation, context_params) { relation.where(author_id: context_params[:author_id]) }
    dimension :approximate_views_count, group: 'ROUND(posts.views_count, -1)'
    filter :is_published, :boolean, conditions: ->(relation) { relation.where(status: 'published') }
  end

  STATUSES = %w(draft private published).freeze

  def to_s
    title
  end
end

Model's Columns

id              integer
author_id       integer
title           string
status          string
published_at    datetime
is_featured     boolean
views_count     integer
created_at      datetime
updated_at      datetime