rails/rails — pull request #12670 by egilburg (2013-10-28 07:11:45+00:00)
Title: Optimize none? and one? relation query methods to use LIMIT 1 and COUNT.

I was surprised to find out that relation's `none?` method was loading the entire collection as an array,
even if no block or limit was given. This contrasts how `any?` and `many?` work, which is to use `LIMIT 1` and `COUNT` respectively, if no block and limit is given.

IMO it's more natural to use `.none?` query rather than either `empty?` (because `empty?` is an Array method while `none?` is an Enumerable method and thus seems more suitable for a generic set such a a set of database rows), or `exists?` (because `exists?` to me implies a zero-vs-one comparison (as opposed to zero, one, or more than one) while `any?` makes so such implications and is again a more generic set operation.

I therefore changed `none?` to follow the already existing behavior for `any?` and `many?`. I then also implemented an optimized `one?` for similar reasons and for completion sake - just as me, others could be surprised that `one?` behaves differently than `any?` and `many?`, and I don't see a drawback to being consistent in providing an efficient implementation if possible.

This change applies to relations (e.g. `User.all`) as well as associations (e.g. `account.users`).

Before:

```ruby
users.none?
SELECT "users".* FROM "users"

users.one?
SELECT "users".* FROM "users"
```

After:

```ruby
users.none?
SELECT 1 AS one FROM "users" LIMIT 1

users.one?
SELECT COUNT(*) FROM "users"
```