在这种情况下,Rails文档似乎很主观。需要注意的是。首先是一样的发现(:第一,等等...)
来源:http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002263
“查找第一个 - 这将返回所使用的选项相匹配的第一个记录这些选项可以是。如果没有记录可以匹配,则返回nil,使用Model.find(:first,* args)或其快捷方式Model.first(* args)。“
挖掘到的ActiveRecord的代码,在base.rb(截至2009年9月5日)的1533线,我们发现:
def find_initial(options)
options.update(:limit => 1)
find_every(options).first
end
这就要求其具有以下定义find_every:
def find_every(options)
include_associations = merge_includes(scope(:find, :include), options[:include])
if include_associations.any? && references_eager_loaded_tables?(options)
records = find_with_associations(options)
else
records = find_by_sql(construct_finder_sql(options))
if include_associations.any?
preload_associations(records, include_associations)
end
end
records.each { |record| record.readonly! } if options[:readonly]
records
end
因为它正在执行一个records.each,所以我不确定这个限制是否仅仅限制了查询运行后它返回的记录数量,但它肯定是这样(不需要我自己进一步挖掘)。似乎你应该使用原始SQL,如果你担心这个性能会受到影响。
这实际上并不适用于mysql(最开始你必须使用'limit 1'而不是'top 1')。在我问这个问题之前,我真的开始使用它,因为它似乎我认为ActiveRecord应该为这样的操作提供一些本地语法支持。如果没有,那就是我需要知道的:) – Daniel 2009-09-05 16:27:49