Encode & Decode
Encode and decode callbacks transform values during serialization and deserialization.
Transforms
Transform values during serialization (encode) and deserialization (decode). Use for presentation transforms — case changes, formatting, normalization.
| Option | When | Direction |
|---|---|---|
encode | Response (output) | Database to API |
decode | Request (input) | API to Database |
INFO
These transformations must preserve the attribute's type. They operate at the serialization layer and are not passed to adapters — invisible to generated TypeScript, Zod, and OpenAPI exports.
# Case normalization: "Invoice" becomes "invoice"
attribute :subjectable_type, encode: ->(v) { v&.underscore }
# Consistent enum format: "pending" becomes "PENDING"
attribute :status,
encode: ->(v) { v&.upcase },
decode: ->(v) { v&.downcase }For null/empty string conversion, use empty: true instead — it affects generated types.
Prefer ActiveRecord Normalizes
For data integrity, use Rails' built-in normalizes instead — it applies everywhere, not just through the API:
class Customer < ApplicationRecord
normalizes :email, with: ->(v) { v&.strip&.downcase }
endEmpty & Nullable
Two options for handling null and empty values.
| Option | Accepts null | Accepts "" | Stores | Returns |
|---|---|---|---|---|
| Default | No | Yes | As-is | As-is |
nullable: true | Yes | Yes | As-is | As-is |
empty: true | No | Yes | nil | "" |
nullable: true
Allow null values in requests and responses:
attribute :bio, nullable: true, writable: true// Request - both valid:
{ "customer": { "bio": "Hello" } }
{ "customer": { "bio": null } }
// Response - returns as stored:
{ "customer": { "bio": null } }empty: true
Convert between nil (database) and "" (API):
attribute :name, empty: true, writable: true// Request with empty string:
{ "customer": { "name": "" } }
// Stored as: nil
// Database has nil:
// Response returns:
{ "customer": { "name": "" } }The database stores NULL for missing values, but the frontend expects empty strings. empty: true handles the conversion.
Examples
- Value Transforms — Transform values during serialization and handle nil/empty conversion