2

I'm able to run this query to generate a hash of Regions and group by answer (including zero count):

Region.includes(:answers).group("regions.region").count("answers")

produces:

{"blar"=>0, "East"=>0, "East Midlands"=>11, "London"=>8, "North East"=>0, "North West"=>0, "Northern Ireland"=>0, "Rest of World"=>89, "Scotland"=>0, "South East"=>0, "South West"=>0, "Wales"=>0, "West Midlands"=>0, "Yorkshire and the Humber"=>0}

However when I want this result (to include count zeros) for a particular question, it only displays a hash of the regions with an answer.

Query:

Region.includes(:answers).where("answers.question_id = 14").group("regions.region").count("answers")

produces:

{"East Midlands"=>3, "London"=>1, "Rest of World"=>4}

I understand the query will be selecting only answers for question_id, so this gives the given output but I've tried many different queries (including LEFT OUT JOINS) and been unable to get the desired result.

For reference:

Region has_many :answers

Answer belongs_to :region

Answer belongs_to :question

Thanks

2 Answers 2

1

For anyone interested, I was able to solve this by adding the sql IS NULL OR to the where clause as so:

Region.includes(:answers).where("answers.id IS NULL OR answers.question_id = 14").group("regions.region").count("answers")

Producing:

{"blar"=>0, "East"=>0, "East Midlands"=>1, "London"=>0, "North East"=>0, "North West"=>0, "Northern Ireland"=>0, "Rest of World"=>4, "Scotland"=>0, "South East"=>0, "South West"=>0, "Wales"=>0, "West Midlands"=>0, "Yorkshire and the Humber"=>0} 

Probably not the best way but it did the job

Sign up to request clarification or add additional context in comments.

Comments

0

Add SELECT with NULLs explicit, like following:

Region.outer_joins(:answers).select('region.name IS NULL').

1 Comment

The result is the same if I include this select method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.