在 Rails 中展开时间序列数据
:fire: Rollup time-series data in Rails
Works great with Ahoy and Searchjoy
Add this line to your application’s Gemfile:
gem "rollups"And run:
bundle install
rails generate rollups
rails db:migrateStore the number of users created by day in the rollups table
User.rollup("New users")Get the series
Rollup.series("New users")
# {
# Thu, 01 Jan 2026 => 50,
# Fri, 02 Jan 2026 => 100,
# Sat, 03 Jan 2026 => 34
# }Use a rake task or background job to create rollups on a regular basis. Don’t worry too much about naming - you can rename later if needed.
Specify the time column - created_at by default
User.rollup("New users", column: :joined_at)Change the default column for a model
class User For multiple series, set a name for each series before charting
series = Rollup.multi_series("Orders by platform")
series.each do |s|
s[:name] = s[:dimensions]["platform"]
endUse any naming convention you prefer. Some ideas are:
New usersnew_usersnew_users.countRename with:
Rollup.rename("Old name", "New name")Rollup stores both dates and times in the time column depending on the interval. For date intervals (day, week, etc), it stores 00:00:00 for the time part. Cast the time column to a date when querying in SQL to get the correct value.
time::dateCAST(time AS date)date(time)Set the default rollup column for your models
class Ahoy::Visit < ApplicationRecord
self.rollup_column = :started_at
endand
class Ahoy::Event < ApplicationRecord
self.rollup_column = :time
endHourly visits
Ahoy::Visit.rollup("Visits", interval: "hour")Visits by browser
Ahoy::Visit.group(:browser).rollup("Visits by browser")Unique homepage views
Ahoy::Event.where(name: "Viewed homepage").joins(:visit).rollup("Homepage views") { |r| r.distinct.count(:visitor_token) }Product views
Ahoy::Event.where(name: "Viewed product").group_prop(:product_id).rollup("Product views")Daily searches
Searchjoy::Search.rollup("Searches")Searches by query
Searchjoy::Search.group(:normalized_query).rollup("Searches by query", dimension_names: ["query"])Conversion rate
Searchjoy::Search.rollup("Search conversion rate") { |r| r.average("(converted_at IS NOT NULL)::int") }View the changelog
Everyone is encouraged to help improve this project. Here are a few ways you can help:
To get started with development:
git clone https://github.com/ankane/rollup.git
cd rollup
bundle install
# create databases
createdb rollup_test
mysqladmin create rollup_test
# run tests
bundle exec rake test暂无开放 Issues,或尚未同步最近议题。