Back to Course

Reading the Source · Card 11

What does attribute add?

A declaration most Rails developers haven't used. It's how you add typed attributes — virtual ones, or overrides for existing columns. Quietly powerful.

The familiar (or maybe unfamiliar) line

Two uses. The first has no matching database column. The second overrides the type of one.

class User < ApplicationRecord
  # 1. Virtual attribute. Not in the schema. Lives only on the instance.
  attribute :discount_percent, :integer, default: 0

  # 2. Override the type of an existing column.
  # Suppose the column `metadata` is text in the DB; treat it as JSON in Ruby.
  attribute :metadata, :json, default: {}
end

The question

What does each of those two attribute calls actually buy you, and when would you reach for them?

Take a moment. Most Rails attributes come from columns automatically. This declaration adds typed attributes on top of that mechanism. Why would you do that?