Tom Hammond
Tom Hammond

Reputation: 6080

Rails Check Number of Child Models

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

Answers (2)

MilesStanfield
MilesStanfield

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

Hieu Pham
Hieu Pham

Reputation: 6707

The query will be:

Campaign.where("id IN (SELECT compaign_id 
                       FROM questions 
                       GROUP BY compaign_id
                       HAVING COUNT(*) > 3")

Upvotes: 1

Related Questions