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?
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?
You may do it by query with join:
Campaign.joins(:responses)
Or by two queries without join:
Campaign.where(id: Response.pluck(:campaign_id))
According to these SO answers, here are a couple of ways you can achieve this:
where.associatedCampaign.where.associated(:responses)
Campaign.includes(:responses).where.not(responses: {id: nil})
or
Campaign.joins(:responses).distinct
Campaign.joins(:responses).distinct
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