In Active Record, why return Article.none rather than [] or nil from a method that callers chain onto, and what SQL does it run?
answer
- a relation that matches nothing
- chainable where [] and nil are not
- no query when loaded or counted
- to_sql shows WHERE (1=0)
- empty? true, count 0, average nil
basics
~20 sArticle.none returns a chainable relation that is known to be empty, so callers can keep adding scopes; loading, counting or checking it returns [], 0 or false without sending any SQL, whereas [] and nil break the chain.
solid answer
~30 s`none` returns an `ActiveRecord::Relation` marked as empty. Because it is still a relation, code such as `visible_articles.featured.order(:published_at)` keeps working, and chained query methods keep the empty marker. Active Record short-circuits on it: loading returns `[]`, `count` and `sum` return `0`, `average`, `minimum` and `maximum` return `nil`, `exists?` returns `false`, and `update_all` or `delete_all` return `0`, none of them touching the database. The relation still renders SQL with `WHERE (1=0)` for `to_sql` or a subquery. Returning `[]` loses every relation method (`[].order` raises `NoMethodError`), and returning `nil` fails on the first chained call.
code
ruby · 7 linesempty = Article.none.where(featured: true).order(:title)
empty.to_a # => [] (no SQL)
empty.count # => 0 (no SQL)
empty.average(:read_time) # => nil (no SQL)
empty.to_sql # => SELECT ... WHERE (1=0) AND ...
[].order(:title) # NoMethodError: Array has no ordergo deeper
Recall that Article.none returns an empty relation you can still chain, unlike [] or nil.
Explain that none short-circuits loading, counting and existence checks without SQL, and why every branch of a filter method should return a relation.
Show that you use none in visibility and search methods, recognise a none branch when an empty page has no query in the log, and test that branch.
Discuss consistent return types across a codebase's query APIs, and how null-object relations reduce defensive code at call sites.
## The problem none solves Methods that decide **which** records a caller may see often have a branch where the answer is "nothing". In a travel magazine, a reader's visible articles depend on their subscription: ```ruby def self.visible_to(reader) case reader&.plan when "premium" then all when "free" then where(premium: false) else none end end Article.published.visible_to(current_reader).featured.order(:published_at) ``` If the last branch returned `[]`, `.featured` would raise `NoMethodError`, because an Array has no scopes. Returning `nil` fails the same way. `none` keeps the return type consistent: every branch returns a relation, so callers never special-case the empty one. ## What none actually is `none` returns a relation with an internal **empty marker**, plus a `WHERE (1=0)` condition so its SQL is still correct if it is ever rendered. Chaining copies the marker: - `Article.none.where(featured: true)` is still empty. - `Article.none.order(:title).limit(5)` is still empty. - `Article.none.to_sql` shows `... WHERE (1=0)`. ## What runs and what does not Active Record checks the marker before talking to the database: | Call | Result | SQL sent | |---|---|---| | `to_a`, `each`, `load` | `[]` | none | | `count`, `sum(:read_time)` | `0` | none | | `average`, `minimum`, `maximum` | `nil` | none | | `exists?`, `any?` | `false` | none | | `empty?`, `none?` | `true` | none | | `update_all`, `delete_all` | `0` | none | The SQL fragment is used only when the relation is embedded in another query, for example as a subquery in `where(id: Article.none.select(:id))`. ## none versus the alternatives 1. **`[]`**: right type for "loaded results", wrong type for "a query"; it cannot take `where`, `order`, scopes or pagination. 2. **`nil`**: forces every caller to guard, and an unguarded chain raises at runtime. 3. **`where("1=0")`** written by hand: chainable, but it runs a real query each time it is loaded or counted. 4. **`where(id: [])`**: an empty `IN` list is recognised as a contradiction, so Active Record also skips the SELECT, but the code reads like an accident rather than a decision, and the shortcut depends on that exact shape. 5. **`none`**: chainable, intention-revealing, and free at runtime. The last two differ in who knows about the emptiness: `none` sets an explicit marker that the short-circuits check first, while the empty-list case is detected by inspecting the conditions when the query is about to run. ## Where it shows up - **Visibility filters**: "records this user may see" methods return `none` for anonymous or unauthorised users. - **Search with invalid input**: a parser that cannot make sense of the query returns `none` instead of raising, and the view renders its normal empty state. - **Associations of unsaved records**: Active Record itself uses the same mechanism, so `Author.new.articles.count` returns `0` without a query. ## none inside scopes `none` also fits inside a scope's lambda when an argument rules out every row. Remember that a scope turns `nil` into `all`, so returning nothing for bad input requires `none` explicitly: ```ruby scope :in_countries, ->(codes) { codes.blank? ? none : where(country_code: codes) } Article.published.in_countries([]).featured # empty, chainable, no SQL ``` Whether an empty filter should mean "no restriction" (`all`) or "no rows" (`none`) is a product decision; the point is to make it explicitly instead of letting `nil` decide. ## Things to watch - `none` hides a branch: an unexpected empty page with no SQL in the log usually means a `none` branch was taken. - Callers that test emptiness should use `empty?` or `any?`, which short-circuit, rather than comparing against `[]`.
- A reader reports an empty article list but the log shows no SELECT for it. What do you suspect?A `none` branch: a relation marked empty returns `[]` without querying, so the missing SQL is the clue. Check the method that builds the list, for example a visibility or search method, for the condition that returned `none`, and test that branch.
- Why does `Article.none.to_sql` still contain a WHERE clause?`none` adds a `1=0` condition besides its empty marker, so if the relation is rendered into SQL, for instance as a subquery inside another query, it still matches no rows instead of matching everything.
- Article.none runs SELECT ... WHERE 1=0 every time it is loaded
- returning [] is equivalent because callers can chain where on it
- calling where on Article.none brings back matching rows
- Article.none.average(:read_time) returns 0
- a class method returning nil is as safe as none for callers that chain