LoginSignup
8
8

More than 5 years have passed since last update.

テーブル一覧や、モデルから has_many, belongs_to, foreign_key を取得する方法

Last updated at Posted at 2017-06-05

モデル構成はこんな感じになっているとします。

hoge.png

テーブル一覧

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"]

以上です。 :walking_tone1:

8
8
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
8
8