No release in over 3 years
activerecord_extras provides utility methods and scopes for ActiveRecord models, including EXISTS and COUNT subqueries on has_many associations, and SQL helpers for boolean casting.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
 Dependencies

Runtime

 Project Readme

ActiveRecord Extras

ActiveRecord Extras provides helpful utility methods and query extensions for ActiveRecord models. It focuses on building SQL subqueries for has_many associations using EXISTS and COUNT, while keeping full composability within ActiveRecord queries.


Features

  • exists_association and count_association methods for Arel-based subqueries
  • Scopes:
    • with_existing(:association)
    • without_existing(:association)
  • Extended select support:
    • with_counts(:association) — includes counts in result sets
    • Accepts optional block for filtering join conditions
  • Fully composable ActiveRecord relations
  • No monkey-patching, Rails 6+ compatible

Installation

Add to your Gemfile:

gem "activerecord_extras"

Then run:

bundle install

Or install manually:

gem install activerecord_extras

Usage

with_existing and without_existing

User.with_existing(:posts)
User.without_existing(:comments)

with_counts

Adds a SELECT COUNT(*) subquery per association:

User.with_counts(:posts)

Supports filtering via block:

User.with_counts(:posts) do |join_condition, posts|
  join_condition.and(posts[:published].eq(true))
end

This produces SQL like:

SELECT users.*, (
  SELECT COUNT(*) FROM posts
  WHERE posts.user_id = users.id AND posts.published = TRUE
) AS posts_count

API Reference

exists_association(association_name, &block)

Returns an Arel EXISTS subquery.

count_association(association_name, &block)

Returns a grouped COUNT(*) Arel subquery.

with_counts(*association_names, &block)

Selects all columns from the model and adds one COUNT subquery per named association. The optional block modifies join conditions.


Development

bundle exec rake test

Tests use SQLite in-memory schema and require no database setup.


License

MIT License © Till Schulte-Coerne