I'm working on a project where I need to scope a model by the number of associated models under a where clause. This is the best I could come up with:
Subscription.where('message_cap > ?', TextMessage.where('created_at > ?', DateTime.now.beginning_of_month).where(subscription: subscription).count)
But, it doesn't work because subscription is undefined. Is there any way in a rails query I can reference the model currently being hit by postgres? I think this is the SQL I'm looking for:
SELECT * FROM 'subscriptions' WHERE 'subscription.message_cap' > (SELECT COUNT(*) FROM 'text_messages' WHERE 'text_messages.subscription_id' = 'subscription.id' AND 'text_message.created_at > BEGINNINGOFMONTH')
This is a really, really performance critical part of my application, so I need it to run in one query if I can.
EDIT
By the way, I'm not sure if the SQL query above is valid. I just put it there to convey the idea of what I was looking for.