在我的 Rails 6/Grape API 应用程序中,我有一个模型 SurveyResult
,我在其中存储用户提交的调查结果。
给定问题的调查结果可能很少(可以是多项选择题):
[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,
例如,相同的 cms_question_id
有两个结果 - 5899779
(如上)。现在,如果我想计算所有用户 SurveyResults
,我将得到以下结果:
[31] pry(main)> SurveyResult.where(survey: survey, user: user).count
=> 3
如何修改此查询以仅计算具有相同 cms_question_id
的 SurveyResult
一次?上述示例的预期结果应为:
[31] pry(main)> SurveyResult.where(survey: survey, user: user).count
=> 2
最佳答案
查看 count
文档将是:
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
关于ruby-on-rails - Ruby .where 只计算一次重复的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63569198/