gpt4 book ai didi

ruby-on-rails - Ruby .where 只计算一次重复的结果

转载 作者:行者123 更新时间:2023-12-04 02:32:20 24 4
gpt4 key购买 nike

在我的 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_idSurveyResult 一次?上述示例的预期结果应为:

[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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com