Noah Clark
Noah Clark

Reputation: 8131

How to count all objects in Database via Active Record

What I'd like to do is count all objects in the database. I started with something like this:

p ["TOTAL COUNT", ApplicationRecord.subclasses.sum(&:count)]

But while experimenting I found...

[5] pry(main)> ApplicationRecord.subclasses.count => 6

Which I expected to return a lot more than that. I can inspect the subclasses and find that some are missing.

Then I found....

[8] pry(main)> ActiveRecord::Base.descendants.count => 10

Which added a few more. Again I can inspect them individually, and I noticed a few were missing. Here is an example of one that is missing...

class MerchantsPrincipal < ApplicationRecord  
end

class Principal < MerchantsPrincipal 
end

How can I make sure those are also included?

Upvotes: 2

Views: 280

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

This is not the answer for your question, but a suggestion for you in order to speed up your test suite.

You can do some caching with FactoryGirl, something like this:

class RecordCache
  def self.[](key)
    all.fetch(key)
  end

  def self.register(name, object)
    all[name] = object
  end

  def self.setup!
    register :admin_user, FactoryGirl.create(:user, is_admin: true)
  end

  private

  def all
    @all ||= {}
  end
end

Then you need to call RecordCache.setup! in your test_helper.rb before running your test suite.

After that, you will be able to ask this RecordCache to provide the instance instead of making FactoryGirl create it again:

FactoryGirl.define do
  factory :post do
    # title content etc.
    user { RecordCache[:admin_user] }
  end
end

So that every time you call FactoryGirl.create(:post), it does not create another user. This brings some concerns, as the same record is cached through the app and should not be modified. But if you want a specific user for a specific context, you can still do:

FactoryGirl.create(:post, user: FactoryGirl.create(:user, :super_admin))

Upvotes: 1

Related Questions