Class.where(id: '1234') 和 Class.find_by id: '1234' 的区别

The difference in Class.where(id: '1234') and Class.find_by id: '1234'

我刚刚发现 .where.find_by 之间的细微差别,显然 .where returns 只有我正在寻找的对象的 _id因为 .find_by returns 是一个散列。有人可以解释一下 Rails 4 和 mongodb 中两种方法的区别吗?

提前致谢

请阅读documentation on the ActiveRecord Query Interface

1 Retrieving Objects from the Database

To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.

The methods are:

...snip...

  • where

All of the above methods return an instance of ActiveRecord::Relation.

所以调用Class.where(...)的结果是一个对象集合。

并且:

1.1.5 find_by

The find_by method finds the first record matching some conditions. For example:

Client.find_by first_name: 'Lifo'
# => #<Client id: 1, first_name: "Lifo">   Client.find_by first_name: 'Jon'
# => nil

(强调我的)

所以调用的结果Class.find_by(...)是第一个找到的对象