AssociationCount 
A small gem for ActiveRecord that allows association counts to be included in your base query.
Installation
Add this line to your application's Gemfile:
gem 'association_count'
And then execute:
$ bundle
Or install it yourself as:
$ gem install association_count
Usage
Include in specific model
Simply add
class Post < ApplicationRecord
extend AssociationCount
# [...]
end
Include in all models
Rails 5, add it to ApplicationRecord
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
# [...]
extend AssociationCount
end
Rails 4, add it to ActiveRecord::Base
ActiveRecord::Base.extend AssociationCount
class Foo < ActiveRecord::Base
has_many :bars
can_count :bars
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
# Each Foo instance will come with a "preloaded" count method: bar_count
Foo.all..map(&:bar_count) # only one SQL query executed
# you can also achieve the same with
foos = Foo.all.association_count(Bar)
This works for any has_many relationship even if it uses non standard foreign keys or is a has_many :x, through: y.
By default the count will be distinct, if this is not desired use:
class Foo < ActiveRecord::Base
has_many :bars
can_count :bars, distinct: false
end
Development
After checking out the repo, run bin/setup to install dependencies. Then, run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release to create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Contributing
- Fork it ( https://github.com/buren/association_count/fork )
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request