モデル構成はこんな感じになっているとします。
テーブル一覧
all_tables
ActiveRecord::Base.connection.tables
(0.6ms) SET NAMES utf8, @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
=> ["ar_internal_metadata", "articles", "companies", "schema_migrations", "users"]
あるテーブルのカラム一覧
columns_of_a_table
User.column_names
=> ["id", "name", "company_id", "created_at", "updated_at"]
has_many で持っているテーブル名
has_many
User.reflect_on_all_associations(:has_many).map(&:name)
=> [:articles]
belongs_to で上にあるテーブル名
belongs_to
User.reflect_on_all_associations(:belongs_to).map(&:name)
=> [:company]
foreign_key を調べる(カラム名は知っている前提)
User.reflections['company'].foreign_key
=> "company_id"
Article.reflections.values.map(&:foreign_key)
=> ["user_id", "category_id"]
おまけ
クラス名文字列をクラスにする方法
"users".classify.constantize
=> User(id: integer, name: string, company_id: integer, created_at: datetime, updated_at: datetime)
これを用いて最初のテーブル一覧の書き方を工夫してみますと。
ActiveRecord::Base.connection.tables.select{|s| s.classify.constantize rescue false}
=> ["articles", "companies", "users"]
以上です。