考虑 ActiveRecord 的以下查找器方法。
.take. 例子。Account.take.limit(1)例子。Account.limit(1)
现在,这两种方法虽然有不同的名称,但它们生成相同的查询:
SELECT "accounts".* FROM "accounts" LIMIT 1
So, what is the difference between .take & .limit(1)? or they are the same?
考虑 ActiveRecord 的以下查找器方法。
.take. 例子。Account.take.limit(1)例子。Account.limit(1)现在,这两种方法虽然有不同的名称,但它们生成相同的查询:
SELECT "accounts".* FROM "accounts" LIMIT 1
So, what is the difference between .take & .limit(1)? or they are the same?
从文档
# File activerecord/lib/active_record/relation/finder_methods.rb, line 64
def take(limit = nil)
limit ? limit(limit).to_a : find_take
end
take返回一个Array记录,同时limit返回一个可以与其他关系链接的 ActiveRecord 关系。
根据API 文档中的代码,不同之处在于limit返回一个Relationwhiletake返回一个Array.
要使用limit你需要一个Relation并且你得到一个关系。要使用take,您还可以使用 Array(因为Array也有take),您还可以得到一个Array. 因此,如果您Array无论如何都想要一个,请使用take并且您不必担心源对象是Relationor Array。
limit(1)将返回一个 ActiveRecord::Relation,这意味着您可以在其上链接更多内容(例如Account.limit(1).where(...).
take将返回一个数组(来自已加载的查询,或者通过执行limit(1)并返回数组)