In an Active Record model, what does attribute :name, :type, default: change for an existing column, and what happens when no column backs it?
answer
- the Attributes API, not attr_accessor
- overrides the schema's cast type
- default: beats the column default
- a proc default runs per new record
- no column: cast, never saved
basics
~20 sOver a column, attribute replaces the type the schema inferred and, with default:, the column's default for new records. Without a column it adds a typed, defaulted virtual attribute that casts input and appears in attributes but is never written to the table.
solid answer
~40 s`attribute` is the Attributes API. On an existing column it **overrides the cast type** the schema chose, so `attribute :deposit_cents, :integer` on a legacy `NUMERIC` column makes reads and writes integers instead of `BigDecimal`, and `where(deposit_cents: "2500")` casts through the same type. `default:` replaces the database default for `Model.new`; a lambda such as `default: -> { Date.current }` is called each time a new value is needed instead of once at boot. With **no column** behind it, the attribute is virtual: it has a reader, writer, casting, a default and dirty tracking, it shows up in `attributes`, but `save` writes nothing for it and there is no column for `where` to filter on. Plain Ruby classes get the same macro by including `ActiveModel::Attributes`.
code
ruby · 13 linesclass Customer < ApplicationRecord
self.table_name = "tbl_customers"
attribute :deposit_cents, :integer # NUMERIC column, Integer in Ruby
attribute :tariff_code, :string, default: "RES-1" # beats the column default
attribute :next_read_on, :date, default: -> { Date.current + 30 }
attribute :autopay_opt_in, :boolean, default: false # no column: virtual
end
c = Customer.new(deposit_cents: "2500", autopay_opt_in: "1")
c.deposit_cents # => 2500
c.autopay_opt_in # => true
c.attributes.key?("autopay_opt_in") # => true, but save never writes itgo deeper
Recall that attribute declares a typed attribute with an optional default, and that one with no column behind it is never saved.
Explain how the declared type replaces the schema's for reads, writes and where, and why a lambda default differs from a plain value.
Judge when a virtual attribute is right (form input a callback consumes) and when a custom type, enum or alias_attribute is the better tool.
Weigh how much type knowledge to put in models versus fixing the schema, given that overrides hide what the database really stores.
## What the attribute macro is Every Active Record attribute already has a **type object** chosen from the column's SQL type (`ActiveModel::Type::Integer`, `ActiveModel::Type::Date`, and so on). The **Attributes API** lets the model take that decision over: ```ruby attribute :name, cast_type = nil, default: ..., **options ``` - `name` is the attribute (and, if one exists, the column it persists to); - `cast_type` is a symbol such as `:string`, `:integer`, `:decimal`, `:boolean` or `:date`, or a type object; - `default:` is a value or a callable; - extra options go to the type's constructor (`limit:`, `precision:`, `scale:`; `array:` and `range:` on PostgreSQL). ## On an existing column: override the type In the utilities-billing app, a legacy `tbl_customers.deposit_cents` column is a `NUMERIC`, so Active Record reads it as a `BigDecimal` (`2500.0`). Declaring `attribute :deposit_cents, :integer`: - **reads** cast through the new type (`2500`, an `Integer`); - **assignment** casts user input (`customer.deposit_cents = "2500"` stores `2500`); - **queries** use it too: `Customer.where(deposit_cents: "2500")` serializes the value through the declared type before building SQL; - **dirty tracking** compares values of the new type. The column in the database is unchanged; only Ruby's view of it moves. ## default: and when it is evaluated Without `default:`, a new record takes the column's database default. With it, the model's value wins: ```ruby attribute :tariff_code, :string, default: "RES-1" attribute :next_read_on, :date, default: -> { Date.current + 30 } ``` | Form | Evaluated | Typical use | |---|---|---| | `default: "RES-1"` | once, when the class is defined | constants | | `default: -> { Date.current + 30 }` | each time a new record needs a value | dates, times, generated values | | no `default:` | the database column default | values the schema already owns | A common bug is `default: Date.current`, which freezes the date the process booted into every new record until the next restart. Use a lambda. ## With no column: a virtual attribute `attribute :autopay_opt_in, :boolean, default: false` on a model whose table has no such column creates a **virtual attribute**: 1. it has a reader and writer, and the writer **casts** (`"0"` and `"false"` become `false`); 2. it honours `default:` and takes part in dirty tracking; 3. it appears in `customer.attributes` and in mass assignment (`Customer.new(autopay_opt_in: "1")`); 4. `save` **writes nothing** for it, since there is no column, and it is no use in `where`: there is no column in the table to filter on. That makes it a good fit for a form checkbox a callback or service reads, and a poor fit for anything that has to survive a reload. ## Outside Active Record: ActiveModel::Attributes The same macro works on a plain Ruby class through `ActiveModel::Attributes`: ```ruby class MeterReadingImport include ActiveModel::API include ActiveModel::Attributes attribute :reading_kwh, :decimal attribute :read_on, :date, default: -> { Date.current } end ``` `ActiveModel::Attributes` supplies the typed, defaulted accessors and `attributes`; `ActiveModel::API` adds the hash initializer, validations and conversion. There is no table, no `save` and no `where`. ## When attribute is the wrong tool - To **rename** a column, use `alias_attribute`; `attribute` does not rename anything. - When a legacy encoding needs custom rules (a `'Y'`/`'N'` flag, money in cents), write a **custom type** object and pass it to `attribute`. - **enum**, **store_accessor** and **serialize** are separate macros built for those shapes; reach for them instead of hand-rolling with `attribute`. ## How it behaves with dirty tracking and forms Because every attribute declared this way has a real type object, the rest of Active Record treats it like a column attribute: - **Dirty tracking compares cast values.** Assigning `"2500"` to an integer attribute that already holds `2500` is **not** a change, so `changed?` stays `false` and no UPDATE is sent. - **Form input is cast once, on assignment.** A checkbox posting `"0"` to a boolean virtual attribute arrives as `false`, so callbacks and services read a real boolean. - **`attributes` and `as_json` include it,** which is handy for a form object and occasionally surprising in an API response. - **Subclasses inherit the declaration** and can redeclare it with another type or default. That consistency is the reason to prefer `attribute` over a hand-written reader and writer pair: the casting rules are the same ones the column attributes already follow.
- Why does attribute :next_read_on, :date, default: Date.current give every customer the same date for days?The argument `Date.current` is evaluated once, when the class body runs at boot, so the default is a fixed date until the process restarts. Passing a lambda, `default: -> { Date.current + 30 }`, makes Active Record call it each time a new record needs the value.
- How would you give a non-persisted import object typed attributes with defaults?Include `ActiveModel::Attributes` (usually with `ActiveModel::API` for the hash initializer and validations) and declare `attribute :reading_kwh, :decimal` and `attribute :read_on, :date, default: -> { Date.current }`. Values cast on assignment and `attributes` returns the hash, but there is no table, `save` or `where`.
The attribute macro is a converter plug fitted to an existing socket: the wall wiring (the column) stays as it is, but everything plugged in now receives the voltage the plug declares, and a plug with no socket behind it still fits devices but powers nothing permanent.
- Saying attribute :deposit_cents, :integer runs an ALTER TABLE to change the column type.
- Writing default: Date.current and expecting a fresh date for each new record.
- Expecting save to persist a virtual attribute that has no column behind it.
- Using attribute to rename a column instead of alias_attribute.
- Treating attribute as a synonym for attr_accessor, with no casting or defaults.