1

I have a very snowballing program that creates a whole heap of records (from different models).

I want to delete the main record, and make sure all the other records associated have also been deleted.

Is there a way to simply count all records in my DB, regardless of what table? Then I can create everything, trigger the main delete, then check if there's anything left in the DB.

1 Answer 1

4
Rails.application.eager_load!
ActiveRecord::Base.subclasses.sum(&:count)
Sign up to request clarification or add additional context in comments.

4 Comments

As a note on large databases with a lot of active writes this can take a consderable amount of time.
Tried this, the second line only returned: [ApplicationRecord(abstract), ActiveRecord::SchemaMigration(version: string)]
@Mirror318, it sounds like you have a non-default subclass between ActiveRecord::Base and your models, e.g. class MyBase < ActiveRecord::Base. Find that subclass and call MyBase.subclasses.sum(&:count).
Oh right, I had a base class called ApplicationRecord, so this worked: ApplicationRecord.subclasses.sum(&:count)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.