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
,不带参数,将“返回模型所有行的计数” 。
那么为什么会有这种行为呢?to_a
一个 AR::Relation 只有在先调用或时才被“加载” 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
因此,也许 usingAR::Relation#size
是对该关系的查询的潜在复杂性大小的度量,其中length
回退到返回记录的计数。