Rails: Comparison of assignable_values and Active Record enum types

Posted . Visible to the public.

We are using assignable_values Show archive.org snapshot for managing enum values in Rails. Nevertheless Rails is adding more support for enum attributes Show archive.org snapshot , allowing to have a closer look at the current feature set in comparison to our still preferred option assignable_values.

Active Record enum attribute interface

By default Rails is mapping enum attributes Show archive.org snapshot to integers:

class Conversation < ActiveRecord::Base
  enum :status, [ :active, :archived ]
end
class CreateConversations < ActiveRecord::Migration[7.1]
  def change
    create_table :conversations do |t|
      t.integer :status

      t.timestamps
    end
  end
end
Conversation.create!(status: 'active')
Conversation.first.status # => 'active'
Conversation.first.attributes_before_type_cast['status'] # => 0

It is still possible to map the enum attribute to an enumerated database type:

class Conversation < ActiveRecord::Base
  enum :status, active: 'active', archived: 'archived'
end
class CreateConversations < ActiveRecord::Migration[7.1]
  def change
    create_enum :status, ['active', 'archived']

    create_table :conversations do |t|
      t.enum :status, enum_type: :status, null: false

      t.timestamps
    end
  end
end
Conversation.create!(status: 'active')
Conversation.first.status # => 'active'
Conversation.first.attributes_before_type_cast['status'] # => 'active'

With the validate option you can add errors to the attribute for unknown attributes:

class Conversation < ActiveRecord::Base
  enum :status, { active: 'active', archived: 'archived' }, validate: true
end
Conversation.create!(status: 'unknown') #=> Validation failed: Status is not included in the list (ActiveRecord::RecordInvalid)

Comparison with assignable_values

But:

  • Better support for the enumerated database type Show archive.org snapshot and therefore better suited for performance optimizations
  • Removing an enum value that exists on records will make their getter return nil
  • Neat features the generated instance methods, prefix/suffix options and scopes
Last edit
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2024-05-13 13:19)