DEV: Change UserField#field_type to an ActiveRecord enum (#27444)

Currently this column is a text column, but by right should only take on one of the values text, confirm, dropdown, multiselect. We can convert this to an ActiveRecord enum instead.

This PR adds a new integer column (field_type_enum) and populates it based on the existing text column (field_type) and adds an alias to replace the latter with the former.
This commit is contained in:
Ted Johansson 2024-06-12 15:30:13 +08:00 committed by GitHub
parent dc8249c08a
commit 5963c03643
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 2 deletions

View File

@ -7,7 +7,7 @@ class UserField < ActiveRecord::Base
deprecate_column :required, drop_from: "3.3"
validates_presence_of :description, :field_type
validates_presence_of :description
validates_presence_of :name, unless: -> { field_type == "confirm" }
has_many :user_field_options, dependent: :destroy
has_one :directory_column, dependent: :destroy
@ -20,6 +20,10 @@ class UserField < ActiveRecord::Base
enum :requirement, { optional: 0, for_all_users: 1, on_signup: 2 }.freeze
# TODO: Drop old field_type and rename this column into field_type and remove alias.
enum :field_type_enum, { text: 0, confirm: 1, dropdown: 2, multiselect: 3 }.freeze
alias_attribute :field_type, :field_type_enum
def self.max_length
2048
end
@ -47,7 +51,7 @@ end
#
# id :integer not null, primary key
# name :string not null
# field_type :string not null
# field_type :string
# created_at :datetime not null
# updated_at :datetime not null
# editable :boolean default(FALSE), not null
@ -60,4 +64,5 @@ end
# external_type :string
# searchable :boolean default(FALSE), not null
# requirement :integer default("optional"), not null
# field_type_enum :integer not null
#

View File

@ -0,0 +1,23 @@
# frozen_string_literal: true
class AddFieldTypeEnumToUserFields < ActiveRecord::Migration[7.0]
def change
add_column :user_fields, :field_type_enum, :integer
up_only do
execute(<<~SQL)
UPDATE user_fields
SET field_type_enum =
CASE
WHEN field_type = 'text' THEN 0
WHEN field_type = 'confirm' THEN 1
WHEN field_type = 'dropdown' THEN 2
WHEN field_type = 'multiselect' THEN 3
END
SQL
change_column_null :user_fields, :field_type, true
change_column_null :user_fields, :field_type_enum, false
end
end
end