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.
exists_associationandcount_associationmethods 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
Add to your Gemfile:
gem "activerecord_extras"Then run:
bundle installOr install manually:
gem install activerecord_extrasUser.with_existing(:posts)
User.without_existing(:comments)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))
endThis produces SQL like:
SELECT users.*, (
SELECT COUNT(*) FROM posts
WHERE posts.user_id = users.id AND posts.published = TRUE
) AS posts_countReturns an Arel EXISTS subquery.
Returns a grouped COUNT(*) Arel subquery.
Selects all columns from the model and adds one COUNT subquery per named association. The optional block modifies join conditions.
bundle exec rake testTests use SQLite in-memory schema and require no database setup.
MIT License © Till Schulte-Coerne