Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails where has_many not empty

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?

like image 958
Tom Hammond Avatar asked Mar 24 '17 18:03

Tom Hammond


1 Answers

You may do it by query with join:

Campaign.joins(:responses)

Or by two queries without join:

Campaign.where(id: Response.pluck(:campaign_id))
like image 53
Ilya Lavrov Avatar answered Sep 23 '22 17:09

Ilya Lavrov