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
- No support for array columns
- No support for allowing values based on other conditions Show archive.org snapshot (e.g. archived is only allowed, when the conversation has no unread messages)
- No support to skip validating values, when they did not change Show archive.org snapshot (e.g. archived is removed as option and the record will be invalid without a data migration)
- No support for Active Record associations Show archive.org snapshot
- No out of the box I18n support for translating the database 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
Posted by Emanuel to makandra dev (2024-05-13 13:19)