Hi there. I’m trying to find the best way to count the number of Users who have one (or many) instances of a has_many relation.
Here’s an example: User has_many :bank_accounts and :credit_accounts (and a few other relations). I want to find the number of unique Users who have at least one bank_account and at least one credit_account, and ideally implement this inside of a scope so I can run where queries on it.
At the moment I’m implementing it (very poorly) using the following code:
(BankAccount.select(:user_id).uniq + CreditAccount.select(:user_id) + ...).uniq.count
I’ve played around a lot with some joins, however I’m not getting any results. For example, I’ve tried
User.joins(:bank_accounts, :credit_accounts).uniq.count however I don’t appear to be getting any results.
Any help would be greatly appreciated, thanks!