Reputation: 6080
Let's say I have a Campaign
model that has_many :questions
.
I want to get all campaigns that have more than 3 questions. So I'd like to do something like this: Campaign.where("questions.length > 3")
Is there a way to do that query?
Upvotes: 1
Views: 57
Reputation: 4639
For a more ActiveRecord looking query to find campaigns that have more than 3 questions, you might try this
Campaign.joins(:questions).group('campaigns.id').having('count(campaign_id) > 3')
Upvotes: 1
Reputation: 6707
The query will be:
Campaign.where("id IN (SELECT compaign_id
FROM questions
GROUP BY compaign_id
HAVING COUNT(*) > 3")
Upvotes: 1