skip to content

In Active Record, why does attribute :paperless, :boolean misread a legacy CHAR(1) 'Y'/'N' column, and how would a custom type fix it?

level: seniorimportance: should knowfreq 30%

answer

  1. Boolean's FALSE_VALUES list
  2. "N" is not in it
  3. cast, deserialize, serialize
  4. where runs serialize too
  5. pass the type object to attribute

basics

~20 s

Active Model's Boolean type treats only values like false, 0, "0", "f" and "false" as false, so "N" casts to true. A custom ActiveRecord::Type::Value that casts "Y"/"N" to booleans and serializes them back keeps reads, writes and where in step.

solid answer

~30 s

`ActiveModel::Type::Boolean` casts by exclusion: `false`, `0`, `"0"`, `"f"`, `"F"`, `"false"`, `"FALSE"`, `"off"` and `"OFF"` become `false`, an empty string becomes `nil`, and anything else, including `"N"`, becomes `true`. Writes are wrong too, because it serializes `true`/`false` rather than `"Y"`/`"N"`. The fix is a type object: subclass `ActiveRecord::Type::Value`, map `"Y"`/`"N"` (and form values) to booleans in `cast_value`, which `cast` and the default `deserialize` both reach, and return `"Y"`/`"N"` from `serialize`. Declare it with `attribute :paperless, YesNoType.new`, or register a symbol with `ActiveRecord::Type.register(:yes_no, YesNoType)`. Because `where` serializes through the attribute's type, `Customer.where(paperless: true)` then sends `'Y'`.

code

ruby · 9 lines
ruby
class Customer < ApplicationRecord
  self.table_name = "tbl_customers"
  attribute :paperless, YesNoType.new
end

c = Customer.find("A-10442")   # row holds 'N'
c.paperless                     # => false
c.update!(paperless: "1")       # writes 'Y'
Customer.where(paperless: true) # WHERE tbl_customers.paperless = 'Y'

go deeper

for a junior

Recall that Rails' boolean cast treats unknown strings such as "N" as true, so legacy Y/N flags need care.

for a middle

Explain which of cast, deserialize and serialize runs on assignment, on read and on save or where.

for a senior

Write the type, decide what unknown values do, and show that queries serialize through it so data and filters stay consistent.

for a principal

Weigh carrying a custom type for a legacy encoding against migrating the column to a native boolean, given other consumers of the table.

## The legacy column The utilities-billing database stores flags the way many old systems did: `tbl_customers.paperless CHAR(1)` holding `'Y'` or `'N'`. Active Record sees a string column, so `customer.paperless` returns `"N"`, and `if customer.paperless` is **always truthy** in Ruby. The tempting fix is one line, and it is wrong. ## Why the built-in boolean type misreads it `ActiveModel::Type::Boolean` casts by **exclusion**: - values in `FALSE_VALUES` (`false`, `0`, `"0"`, `"f"`, `"F"`, `"false"`, `"FALSE"`, `"off"`, `"OFF"` and their symbols) become `false`; - an empty string becomes `nil`; - **everything else becomes `true`**. `"N"` is not on the list, so after `attribute :paperless, :boolean` every customer reads as paperless. Writing is broken as well: the type serializes `false` as a boolean, not as `'N'`, so the database receives a value in the wrong encoding. ## The three conversions a type owns A type object sits on every path a value travels: | Method | Called when | Input | Returns | |---|---|---|---| | `cast(value)` | assignment from code or params | `"1"`, `true`, `"Y"` | the Ruby value | | `deserialize(value)` | reading a row from the database | `"Y"` / `"N"` | the Ruby value (default: calls `cast`) | | `serialize(value)` | saving, and building `where` conditions | `true` / `false` | the database value | `cast` itself returns `nil` for `nil` and otherwise calls the private `cast_value`, so overriding `cast_value` covers both assignment and, through the default `deserialize`, reads. ## A YesNoType ```ruby class YesNoType < ActiveRecord::Type::Value def type = :yes_no def serialize(value) case cast(value) when true then "Y" when false then "N" end end private def cast_value(value) case value when "Y", "y", true, "1", "true" then true when "N", "n", false, "0", "false" then false end end end ``` Then in the model: ```ruby attribute :paperless, YesNoType.new ``` After this: 1. reading a row with `'N'` gives `false`; 2. a form checkbox posting `"1"` or `"0"` casts to `true` or `false`; 3. `save` writes `'Y'` or `'N'`; 4. `Customer.where(paperless: true)` serializes through the same type and sends `paperless = 'Y'`. ## Registering a symbol `ActiveRecord::Type.register(:yes_no, YesNoType)` lets models write `attribute :paperless, :yes_no`. Registration usually lives in an initializer, and Rails does not allow autoloading reloadable application code while the app boots, so a registered type class belongs somewhere initializers may load (for example `lib/` set up with `config.autoload_lib_once`), or the model can simply pass `YesNoType.new` and skip registration. ## Design notes - **Inherit from an existing type** when one is close: an `ActiveRecord::Type::Integer` subclass that strips `$` before casting is the documented money example. - **Decide what unknown input does.** The sketch above returns `nil` for anything else; raising may suit an import better. - **Mutable values** (hashes, arrays) need attention to `changed_in_place?`, which dirty tracking calls to notice in-place edits; immutable booleans do not. - **Prefer built-ins** when the column can change: migrating `paperless` to a real `boolean` column removes the need for any of this. ## Testing the type A custom type is a small object with no database dependency, so it is easy to test directly, and worth testing because every read and query goes through it: 1. `YesNoType.new.cast("Y")` returns `true`, `cast("N")` returns `false`, `cast(nil)` returns `nil`. 2. `YesNoType.new.deserialize("N")` returns `false`, proving reads from the table are right. 3. `YesNoType.new.serialize(true)` returns `"Y"` and `serialize("0")` returns `"N"`, proving form input is written in the legacy encoding. 4. A model-level check, `Customer.where(paperless: true).to_sql`, contains `'Y'`, which proves queries and saves agree. The fourth check is the one teams skip and regret: a type whose `serialize` disagrees with what the database holds produces filters that silently return nothing.

  • Why override cast_value rather than cast in a custom Active Record type?
    `ActiveModel::Type::Value#cast` already returns `nil` for `nil` and calls the private `cast_value` for everything else, and the default `deserialize` calls `cast`. Overriding `cast_value` therefore covers assignment and database reads at once, with nil handling inherited.
  • With the custom type in place, what does Customer.where(paperless: false) send to the database, and why?
    `paperless = 'N'`. Hash conditions in `where` serialize the value through the attribute's declared type, so `false` goes through `YesNoType#serialize` and becomes `'N'`, the same encoding `save` writes.

  • Assuming attribute :paperless, :boolean casts "N" to false like a database boolean would.
  • Overriding only deserialize and forgetting that assignment and where use cast and serialize.
  • Expecting where(paperless: true) to send a SQL boolean literal even after a custom type.
  • Registering an autoloaded type class from an initializer and expecting it to reload.
  • Claiming deserialize is what runs when a form assigns paperless = "1".