Skip to content

Instantly share code, notes, and snippets.

@patorash
Created February 24, 2021 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patorash/7b4559e12bf3a73ef3ff769ed99b4c89 to your computer and use it in GitHub Desktop.
Save patorash/7b4559e12bf3a73ef3ff769ed99b4c89 to your computer and use it in GitHub Desktop.
Add column comment from ActiveRecord::Enum. with enum_help gem.
class AddColumnCommentFromEnum < ActiveRecord::Migration[6.0]
def up
table_with_columns.each do |table_name, columns|
next unless I18n.exists?("enums.#{table_name.singularize}")
columns.map(&:name).each do |column_name|
next unless I18n.exists?("enums.#{table_name.singularize}.#{column_name}")
model = table_name.classify.constantize
enums = model.send(column_name.pluralize)
enums_i18n = enums.map { |k, v| [model.send("#{column_name.pluralize}_i18n")[k], v] }
change_column_comment(
table_name,
column_name,
"#{I18n.t("activerecord.attributes.#{table_name.singularize}.#{column_name}")}:#{enums_i18n.to_h.invert.to_s}",
)
end
end
end
def down
table_with_columns.each do |table_name, columns|
next unless I18n.exists?("enums.#{table_name.singularize}")
columns.map(&:name).each do |column_name|
next unless I18n.exists?("enums.#{table_name.singularize}.#{column_name}")
change_column_comment(
table_name,
column_name,
I18n.t("activerecord.attributes.#{table_name.singularize}.#{column_name}"),
)
end
end
end
private
def table_with_columns
system_view_names = %w(
pg_stat_statements
geography_columns
geometry_columns
raster_columns
raster_overviews
)
tables = ApplicationRecord.connection.tables
views = ApplicationRecord.connection.views - system_view_names
(tables + views).each_with_object({}) { |table, hash| hash[table] = ApplicationRecord.connection.columns(table) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment