使用活动记录时,如何列出为数据库定义的所有表?
时间:2020-03-06 14:56:23 来源:igfitidea点击:
使用活动记录时,如何获取为数据库定义的所有表的列表?
解决方案
不知道活动记录,但这是一个简单的查询:
选择表名
来自INFORMATION_SCHEMA.Tables
其中TABLE_TYPE ='BASE TABLE'
似乎应该有一个更好的方法,但是这是我解决问题的方法:
Dir["app/models/*.rb"].each do |file_path| require file_path # Make sure that the model has been loaded. basename = File.basename(file_path, File.extname(file_path)) clazz = basename.camelize.constantize clazz.find(:all).each do |rec| # Important code here... end end
此代码假定我们遵循类和源代码文件的标准模型命名约定。
调用ActiveRecord :: ConnectionAdapters :: SchemaStatements#tables
。该方法在MySQL适配器中没有记录,但在PostgreSQL适配器中有记录。 SQLite / SQLite3也已实现了该方法,但未记录。
>> ActiveRecord::Base.connection.tables => ["accounts", "assets", ...]
参见activerecord / lib / active_record / connection_adapters / abstract / schema_statements.rb:21
,以及此处的实现:
activerecord / lib / active_record / connection_adapters / mysql_adapter.rb:412
activerecord / lib / active_record / connection_adapters / postgresql_adapter.rb:615
activerecord / lib / active_record / connection_adapters / sqlite_adapter.rb:176