ActiveRecord查找现有表索引

Sea*_*ary 34 sql database activerecord ruby-on-rails

我正在为我正在编写的插件编写一个迁移生成器,我需要能够找到表中的唯一索引,以便我可以修改现有的唯一索引以成为复合唯一索引.我一直试图找到一种方法来访问表与ActiveRecord的索引.我只能找到ActiveRecord :: ConnectionAdapters :: PostgreSQLAdapter :: indexes方法,但不幸的是,这只适用于PosgreSQLAdapter.我需要能够支持其他主要数据库.

我首先使用schema.rb文件来查找索引,这首先起作用,但我很快意识到这是一个糟糕的策略.

我想如果ActiveRecord没有提供能够为多个数据库适配器执行此操作的方法,我可能能够编写特定于适配器的查询以从表中检索索引信息.如果我需要采用这种方法,那么确定正在使用的适配器的好方法是什么?

如果有人知道如何让ActiveRecord列出理想的表索引信息.

小智 77

这适用于MySQL,SQLite3和Postgres:

ActiveRecord::Base.connection.tables.each do |table|
    puts ActiveRecord::Base.connection.indexes(table).inspect
end
Run Code Online (Sandbox Code Playgroud)

但我认为它只会为您提供专门创建的索引.

另外,要找出正在使用的适配器:

ActiveRecord::Base.connection.class
Run Code Online (Sandbox Code Playgroud)


Abi*_*lah 23

只是更清洁检查的更新.由于我有很多桌子,我发现很难搜索特定的东西.

  ActiveRecord::Base.connection.tables.each do |table|
  indexes = ActiveRecord::Base.connection.indexes(table)
  if indexes.length > 0
    puts "====>  #{table} <===="
    indexes.each do |ind|
      puts "----> #{ind.name}"
    end
    puts "====>  #{table} <===="
    2.times{ puts ''}
  end
end
Run Code Online (Sandbox Code Playgroud)

这将是快速设置.


Jas*_*ett 10

如果您只想查看特定表的所有索引,您可以执行以下操作:

ActiveRecord::Base.connection.indexes('my_table_name').map(&:name)
Run Code Online (Sandbox Code Playgroud)