Table with Aggregations
If you'd like to add rows or columns that aggregate the table's data, you can use report_options.aggregations
. Currently, the only supported operator is sum
, but others may be supported in the future.
For example, if you want to add a row at the bottom of a table that shows the sum of each column and a column at the end of the table that shows the sum of each row, use the following:
report_options:
aggregations:
- from: columns
operator: sum
label: Total
- from: rows
operator: sum
label: Total
To create the chart above, simply add the following YAML file and call render_report
in any view:
YAML
config/reports_kit/reports/table_with_aggregations.yml
measure: post filters: - key: author - key: created_at criteria: operator: between value: "-3M - now" dimensions: - key: tags label: Tag - key: author limit: 5 order: dimension1.label format: table report_options: aggregations: - from: columns operator: sum label: Total - from: rows operator: sum label: Total
View
app/views/my_controller/my_view.html.haml
= render_report 'table_with_aggregations' do |report| = report.form do |f| .pull-right = f.date_range :created_at = f.multi_autocomplete :author, placeholder: 'Author...'
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