In my Rails 6/Grape API app I've got a model SurveyResult where I store results of survey which user filed.
It's possible to have few survey results for a given question (it can be a multiple choice question):
[31] pry(main)> SurveyResult.where(survey: survey, user: user)
#<SurveyResult:0x00007f9283adca10
id: 18,
user_id: 1,
survey_id: 1,
cms_question_id: 5844869,
cms_answer_id: 321,
#<SurveyResult:0x00007f9283adc7e0
id: 20,
user_id: 1,
survey_id: 1,
cms_question_id: 5899779,
cms_answer_id: 0987,
#<SurveyResult:0x00007f9283adc920
id: 21,
user_id: 1,
survey_id: 1,
cms_question_id: 5899779,
cms_answer_id: 12,
For example there are two results for the same cms_question_id - 5899779 (as above). Now if I want to count all user SurveyResults I will get below result:
[31] pry(main)> SurveyResult.where(survey: survey, user: user).count
=> 3
How to modify this query to count SurveyResult with the same cms_question_id only once? The expected result for above example should be:
[31] pry(main)> SurveyResult.where(survey: survey, user: user).count
=> 2
Looking at the count documentation that would be:
SurveyResult.where(survey: survey, user: user).distinct.count(:cms_question_id)
count(column_name = nil)
Count the records.
Person.count # => the total count of all people Person.count(:age) # => returns the total count of all people whose age is present in database Person.count(:all) # => performs a COUNT(*) (:all is an alias for '*') Person.distinct.count(:age) # => counts the number of different age values
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With