Skip to content

Instantly share code, notes, and snippets.

@digitalm
Created June 28, 2022 16:24
Show Gist options
  • Save digitalm/e6b41f1b556418c42787d5fa74669779 to your computer and use it in GitHub Desktop.
Save digitalm/e6b41f1b556418c42787d5fa74669779 to your computer and use it in GitHub Desktop.
ActiveRecord経由でrailsアプリのすべてのテーブル、スキーマのハッシュを取得するスニペット
# { 'Org' => ['id:integer','name:string'],
# 'User' => ['id:integer','email:string'] }
#
# NOTE: If there is no corresponding model in the DB, it will warn.
err = []
ActiveRecord::Base.connection.tables.each_with_object({}) do |table_name, hash|
begin
next if table_name == 'schema_migrations'
next if table_name == 'ar_internal_metadata'
key = table_name.singularize.camelize
value = eval("#{key}.column_names").each_with_object([]) do |column, array|
column_type = eval("#{key}.columns_hash[column].type")
array << "#{column}:#{column_type}"
end
hash[key] = value
rescue NameError => e
err << "hey, don't seem to have a model but exist table: #{e.message}"
end
end
puts err.map(&:red)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment