Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Active Record Models

Attributes, Types and Enums

Learn how Active Record casts values into Ruby types, how to declare enums, defaults and the attributes API, and how to store JSON and secure data. Includes a runnable enum and type-cast stand-in.

Everything a form or request sends arrives as a string. A database column has a real type: integer, boolean, date, decimal. Active Record sits between them and casts values, so article.views = "42" becomes the integer 42 and "1" or "true" becomes true. On top of that you can describe your own attributes, set defaults, store structured data in a column, and turn a status column into readable names with enums.

The Rails snippets are read-only. The stand-ins implement type casting and an enum macro in plain Ruby so you can see the generated methods.

Type casting

Active Record reads each column's type from the table and applies it whenever you assign:

Ruby
# read-only: rails console
article = Article.new(views: "42", published: "false", rating: "4.5")
article.views       # => 42        (integer)
article.published   # => false     (boolean: "false", "0", "f", "off" are false)
article.rating      # => 4.5       (float or decimal)
article.views_before_type_cast   # => "42"

Invalid input is cast leniently. A string like "abc" for an integer column becomes 0 or nil depending on the type, and no error is raised. That is one reason validations such as numericality exist (validations).

Declaring attributes and defaults

You can declare or override an attribute in the model. This is useful for defaults, for virtual attributes that are not columns, and for custom types.

Ruby
# read-only
class Article < ApplicationRecord
  attribute :views, :integer, default: 0
  attribute :tags_text, :string          # virtual: not a column
  attribute :published_on, :date, default: -> { Date.current }
end

A column-level default (in the migration, default: false) is usually better when every writer to the database should share it. A model-level default is fine for application-only values. Remember null: false plus a default in the migration for flags, as in migrations.

Enums

Many columns hold one of a few named states: an article is draft, published or archived. An enum maps names to values and generates helper methods.

Ruby
# read-only
class Article < ApplicationRecord
  enum :status, { draft: 0, published: 1, archived: 2 }, default: :draft
end
Ruby
# read-only: generated methods
article.draft?          # => true
article.published!      # updates status and saves
article.status          # => "published"
article.status = :archived
Article.published      # scope: WHERE status = 1
Article.not_archived   # negative scope (via prefix options)
Article.statuses        # => { "draft" => 0, "published" => 1, "archived" => 2 }

The column is an integer (t.integer :status, default: 0, null: false), so the database stays compact while the code reads like English. Two details matter:

  • Assigning an unknown name raises ArgumentError, so typos fail loudly. Add validate: true to get a normal validation error instead, which suits form input.
  • Name clashes. Two enums that both define active would collide. Use prefix: or suffix: (enum :role, { admin: 0, user: 1 }, prefix: true gives role_admin?).

Strings work too ({ draft: "draft", published: "published" }), which makes the data readable in the database, at the cost of slightly more space.

What an enum gives you

Predicates article.draft?
Bang setters article.published!
Scopes Article.published
1 / 2

Stand-in: an enum macro

This stand-in builds the macro with define_method. Notice how one declaration creates predicates, setters, scopes and validation.

Ruby Stand-in: enum predicates, bang methods and scopes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The real enum also adds negative scopes, validations, support for prefix: and suffix:, and database-aware querying (where(status: :published)), but the core is the same.

Type casting stand-in

Here is how casting a string input to a typed value can work. The cast function is similar in spirit to Active Record's type classes (ActiveModel::Type::Integer, Boolean and so on).

Ruby Stand-in: casting strings to Ruby types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Casting never raises for bad user input; it yields nil or a default. Never trust the cast result as validated data. Validate it, as the next chapters show.

JSON, arrays and encrypted attributes

Modern databases can hold structured data. With PostgreSQL, MySQL or SQLite you can use a json column and Active Record gives you a Hash:

Ruby
# read-only
# migration: t.json :settings, default: {}
user.settings = { "theme" => "dark" }
user.settings["theme"]           # => "dark"

class User < ApplicationRecord
  store_accessor :settings, :theme, :locale     # user.theme, user.theme = "light"
end

Rails can also encrypt a column transparently:

Ruby
# read-only
class User < ApplicationRecord
  encrypts :phone_number                        # stored encrypted, decrypted when read
  encrypts :email, deterministic: true          # same input gives same ciphertext, so you can query it
end

Encryption needs keys in the credentials file (bin/rails db:encryption:init prints them). Use it for personal data such as tokens, phone numbers or health data; passwords have their own tool, covered in authentication.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does article.views = "42" store for an integer column?

    Active Record casts the assigned value to the column's type.
  2. 2. What does enum :status, { draft: 0, published: 1 } generate?

    An enum creates readable helper methods for each named value.
  3. 3. What happens by default when you assign an unknown enum name?

    Invalid enum values fail loudly unless you add validate: true.
  4. 4. Why use prefix: true on an enum?

    A prefix generates names like role_admin? so two enums can both have an admin or active value.
  5. 5. Why is it risky to reorder the integer values of an existing enum?

    The database stores the numbers, so changing the mapping changes the meaning of existing data.

Summary

  • Active Record casts assigned values to the column type; bad input becomes nil or a default, so always validate.
  • attribute declares defaults, virtual attributes and custom types; database defaults are better for shared rules.
  • enum maps names to stored values and generates predicates, bang setters, scopes and validation options.
  • Use prefix:/suffix: to avoid clashes and never reuse or reorder stored enum values.
  • json columns, store_accessor and encrypts cover structured and sensitive data.

Next: Associations: belongs_to and has_many