r.respondents.select(:name).uniq 返回一个 ActiveRecord::Relation 对象,该对象覆盖size。
见:http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-size
对此类对象调用size 会检查该对象是否“已加载”。
# Returns size of the records.
def size
loaded? ? @records.length : count
end
如果是“已加载”,则返回@records 数组的长度。否则,它会调用count,如果没有参数,它将“return a count of all the rows for the model.”
那么为什么会有这种行为呢? AR::Relation 只有在首先调用 to_a 或 explain 时才会“加载”:
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation.rb
load 方法上方的评论解释了原因:
# Causes the records to be loaded from the database if they have not
# been loaded already. You can use this if for some reason you need
# to explicitly load some records before actually using them. The
# return value is the relation itself, not the records.
#
# Post.where(published: true).load # => #<ActiveRecord::Relation>
def load
unless loaded?
# We monitor here the entire execution rather than individual SELECTs
# because from the point of view of the user fetching the records of a
# relation is a single unit of work. You want to know if this call takes
# too long, not if the individual queries take too long.
#
# It could be the case that none of the queries involved surpass the
# threshold, and at the same time the sum of them all does. The user
# should get a query plan logged in that case.
logging_query_plan { exec_queries }
end
self
end
因此,也许使用AR::Relation#size 来衡量此关系上查询的潜在复杂性的大小,其中length 回退到返回记录的计数。