【发布时间】:2019-08-01 21:27:08
【问题描述】:
我想从 db/schema.rb 文件创建一个 CSV/Excel 文件。我可以将表名及其属性名转储到文件中,但我也想转储其他信息,例如索引和列约束等。
这是我的代码
require 'write_xlsx'
Rails.application.eager_load!
# Create a new Excel workbook
workbook = WriteXLSX.new('schema.xlsx')
# Add a worksheet
worksheet = workbook.add_worksheet
# Add and define a format
format = workbook.add_format # Add a format
format.set_bold
format.set_color('red')
format.set_align('center')
# Write a formatted and unformatted string, row and column notation.
col = row = 0
worksheet.write(0, 0, 'Table Name')
worksheet.write(0, 1, 'Attributes')
worksheet.write(0, 2, 'Attribute Type')
worksheet.write(0, 3, 'Attribute constraints')
worksheet.write(0, 4, 'Comments')
ApplicationRecord.descendants.each_with_index do |model, _index|
row += 1
worksheet.write(row, 0, model.name)
worksheet.write(row, 1, '')
model.attribute_types.each_pair do |attribute, attribute_type|
row += 1
worksheet.write(row, 1, attribute)
worksheet.write(row, 2, attribute_type.type)
worksheet.write(row, 3, JSON.parse(attribute_type.to_json))
end
end
workbook.close
我也从 PG 管理员那里尝试过,但得到了预期的结果。
COPY (select * from information_schema.columns) TO '/home/sachin/ruby/profile_service/columns.csv' with delimiter ',' csv header;
【问题讨论】:
-
您需要程序化解决方案吗?如果没有,您可以使用 Postico 之类的工具运行查询
select * from information_schema.columns,然后将结果导出为 CSV。 -
@aridlehoover 是的,我需要一个程序化解决方案。这将显示约束和索引以及表的列。
-
我强烈建议您熟悉 ActiveRecord::SchemaDumper。 github.com/rails/rails/blob/master/activerecord/lib/…
标签: ruby-on-rails ruby excel csv schema