Datetime

A datetime filter lets you filter the report by either a datetime column or by some custom expression that evaluates to a datetime.

Datetime Column

If the model has a datetime created_at column, you can use the following to only count records which were created in the last three months:

measure: post
filters:
- key: created_at
  criteria:
    operator: between
    value: -3M - now
dimensions:
- author

You'll typically want to use relative time for the filter, so ReportsKit provides simple abbreviations for time units. For example, -3w is converted to 3.weeks.ago.

y - years
M - months
w - weeks
d - days
h - hours
m - minutes
s - seconds

Custom Filter

To use a custom SQL expression instead of a column, define it in the model:

class Post < ApplicationRecord
  include ReportsKit::Model
  reports_kit do
    filter :author_created_at, :datetime, joins: :author, column: 'authors.created_at'
  end
end

And then use it in the YAML:

measure:
  key: post
  name: New Authors' Posts
filters:
- key: author_created_at
  criteria:
    operator: between
    value: -3M - now
dimensions:
- author

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

YAML

config/reports_kit/reports/filter_datetime.yml

measure: post
filters:
- key: created_at
  criteria:
    operator: between
    value: "-3M - now"
dimensions:
- author

View

app/views/my_controller/my_view.html.haml

= render_report 'filter_datetime' do |report|
  = report.form do |f|
    .pull-right
      = f.date_range :created_at

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