Median for ActiveRecord
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.

README.md

ActiveMedian

Median for ActiveRecord

PostgreSQL only, as MySQL only supports aggregate user-defined functions in C and C++, and SQLite only supports them in C

Build Status

Usage

Item.median(:price)

Works with grouping, too.

Order.group("date_trunc('week', created_at)").median(:total)

Installation

Add this line to your application’s Gemfile:

gem 'active_median'

And create a migration to add the median function to the database.

rails g migration create_median_function

with:

def up
  ActiveMedian.create_function
end

def down
  ActiveMedian.drop_function
end

Rails can’t store functions in schema.rb, so add to your Rakefile:

Rake::Task["db:schema:load"].enhance do
  ActiveMedian.create_function
end

Or change the dump format to sql in config/application.rb:

config.active_record.schema_format = :sql

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help: