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

标签 ruby-on-rails ruby

在我的 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/

相关文章:

ruby-on-rails - 在 Ruby 中解析复杂的 URL

html - Rails sanitizer : Allow certain styles in style attribute

ruby-on-rails - 如何将 Rails 从 3.2.7 更新到 4.0?

ruby - 如何将参数从父任务传递到 Rake 中的子任务?

ruby-on-rails - ocsp 通过传递证书文本而不是文件来验证证书

mysql - 错误命名迁移 - rake db :migrate rejected

ruby-on-rails - sqlite3.rb :6:in require: libruby. so.2.2: 无法打开共享对象文件

ruby-on-rails - Rspec should_receive 在一个没有行为的实例上

javascript - 没有验证的属性上的客户端验证成功消息?

arrays - 数组索引 0 设置为一个变量,然后返回 nil 值,Ruby