ActiveRecordで全てのtable nameと全てのcolumn nameを得る
Rails ActiveRecord
Get all table names
code:ruby
# <= 5.2
ApplicationRecord.connection.tables
# 5.2 <
ActiveRecord::Base.connection.tables
Get all columns of a table
code:ruby
ApplicationRecord.connection.columns('users').map(&:name)
ActiveRecord::Base.connection.columns('users').map(&:name)
# columns が返すのは Array<ActiveRecord::ConnectionAdapters::PostgreSQLColumn> のようなオブジェクト (PostgreSQLの場合)
# または以下
User.column_names
Get all columns of all tables
code:ruby
csv = CSV.generate(col_sep: "\t") do |csv|
ActiveRecord::Base.connection.tables.sort.each do |table_name|
next if 'schema_migrations', 'ar_internal_metadata'.include? table_name # その他にもgemなどが依存するtableが邪魔なら除く
ActiveRecord::Base.connection.columns(table_name).each do |column|
csv << table_name, column.name
end
end
end
MongoMapperで全てのtable nameと全てのcolumn nameを得ることもできる
参考
https://stackoverflow.com/questions/154372/how-to-list-of-all-the-tables-defined-for-the-database-when-using-active-record