15

My Campaign model has_many Response.

What I'd like to do is a search that's like Campaign.where.not(responses.nil?)

Basically returning a list of all campaigns that have responses.

What's the best way to do this?

Tom Hammond
  • 5,842
  • 12
  • 52
  • 95

3 Answers3

13

You may do it by query with join:

Campaign.joins(:responses)

Or by two queries without join:

Campaign.where(id: Response.pluck(:campaign_id))
Ilya Lavrov
  • 2,810
  • 3
  • 20
  • 37
5

According to these SO answers, here are a couple of ways you can achieve this:

Rails 7+ where.associated

Campaign.where.associated(:responses)

Rails 4+

Campaign.includes(:responses).where.not(responses: {id: nil})

or

Campaign.joins(:responses).distinct

Rails 3+

Campaign.joins(:responses).distinct

References:

3

You could do a SQL join to return only the Campaign records with Responses, like this: Campaign.joins(:responses)

It will produce SQL like: SELECT campaigns.* FROM campaigns INNER JOIN responses ON responses.campaign_id = campaign.id