LoginSignup
3
3

More than 5 years have passed since last update.

ActiveRecordでテーブルステータスを取得する

Posted at

Railsアプリケーションの開発中にテーブルの作成日時が欲しくなったので、やり方を調べたりしたので共有です。参考にしたのは、rails/abstract_mysql_adapter.rb#L135 あたりのコードです。

# HACK: クラスを再オープンしてクラスメソッドを定義する
class ActiveRecord::Base
  def self.table_status
    query = "SHOW TABLE STATUS LIKE '#{self.table_name}'"
    connection.select_one(query)
  end
end
irb(main):001:0> User.table_status
   (1.7ms)  SHOW TABLE STATUS LIKE 'users'
=> {"Name"=>"users",
 "Engine"=>"InnoDB",
 "Version"=>10,
 "Row_format"=>"Compact",
 "Rows"=>10,
 "Avg_row_length"=>1638,
 "Data_length"=>16384,
 "Max_data_length"=>0,
 "Index_length"=>180224,
 "Data_free"=>0,
 "Auto_increment"=>11,
 "Create_time"=>2015-02-28 07:48:06 +0900,
 "Update_time"=>nil,
 "Check_time"=>nil,
 "Collation"=>"utf8_unicode_ci",
 "Checksum"=>nil,
 "Create_options"=>"",
 "Comment"=>""}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3