LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】多数のテーブルが存在する場合においてアソシエーションの一覧を取得する

Posted at

概要

本記事は数百個のテーブルが存在するアプリケーションの開発をしている中で、あるモデルがどのモデルに対してアソシエーションの関係があるかを一覧で把握したいことがあった際に、アソシエーションの情報を一覧で取得できるコマンドを考えた際のメモになります。

コマンド

Railsコンソールで実行

has_many

hash = {}
tables = ActiveRecord::Base.connection.tables
tables.each do |table|
 value = table.classify.constantize.reflect_on_all_associations(:has_many).map(&:name) rescue false
 hash.store(table, value)
end

has_one

hash = {}
tables = ActiveRecord::Base.connection.tables
tables.each do |table|
 value = table.classify.constantize.reflect_on_all_associations(:has_one).map(&:name) rescue false
 hash.store(table, value)
end

belongs_to

hash = {}
tables = ActiveRecord::Base.connection.tables
tables.each do |table|
 value = table.classify.constantize.reflect_on_all_associations(:belongs_to).map(&:name) rescue false
 hash.store(table, value)
end

 出力イメージ

"hoge"=>[],
"fuga"=>false,
"piyo"=>[],
"hogehoge"=>[],
"fugafuga"=>[],
"piyopiyo"=>[],
"hogefuga"=>[],
"fugapiyo"=>[:fugafuga, :hoge],
0
0
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
0
0