[10] pry(main)> r.respondents.select(:name).uniq.size

(1.1ms)  SELECT DISTINCT COUNT("respondents"."name") FROM "respondents"
INNER JOIN "values" ON "respondents"."id" = "values"."respondent_id" WHERE
"values"."round_id" = 37 => 495

[11] pry(main)> r.respondents.select(:name).uniq.length

Respondent Load (1.1ms)  SELECT DISTINCT name FROM "respondents"
INNER JOIN "values" ON "respondents"."id" = "values"."respondent_id" WHERE
"values"."round_id" = 37 => 6

为什么每个查询返回的内容不同?

最佳答案

.count #=> this always triggers a SELECT COUNT(*) on the database

.size #=> if the collection has been loaded, defers to Enumerable#size, else does the SELECT COUNT(*)

.length #=> always loads the collection and then defers to Enumerable#size

关于sql - 复杂的 ActiveRecord 案例中的大小、长度和计数之间的差异,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11905364/

10-11 21:32