Activerecord::Reflection の .reflections でモデルの関連情報を取得する

2025-02-09

レシーバに指定したクラスの関連情報が、table 名の文字列を key、関連情報をもったクラスのインスタンスを value とした Hash として返ってくる。

“関連情報をもったクラスのインスタンス” は関連の種類によって異なり、has_many は ActiveRecord::Reflection::HasManyReflection、has_one は ActiveRecord::Reflection::HasOneReflection、belongs_to は ActiveRecord::Reflection::BelongsToReflection が返ってくる。through や has_and_belongs_to_many 用の Reflection クラスもある。

以下のように、関連を指定したときのオプションが @options の中に入っているので、hash['entries'].options[:dependent].present? のようにして :dependent オプションが指定されているかどうかを確認できる。

{"entries" =>
  #<ActiveRecord::Reflection::HasManyReflection:0x0000ffff67ac9560
   @active_record=Channel (call 'Channel.load_schema' to load schema informations),
   @association_foreign_key=nil,
   @association_primary_key=nil,
   @class_name=nil,
   @counter_cache_column=nil,
   @foreign_key=nil,
   @inverse_of=nil,
   @inverse_which_updates_counter_cache=nil,
   @inverse_which_updates_counter_cache_defined=false,
   @join_table=nil,
   @klass=nil,
   @name=:entries,
   @options={dependent: :destroy},
   @plural_name="entries",
   @scope=nil>,
 "workspace" =>
  #<ActiveRecord::Reflection::BelongsToReflection:0x0000ffff67b3fa08
   @active_record=Channel (call 'Channel.load_schema' to load schema informations),
   @association_foreign_key=nil,
   @association_primary_key=nil,
   @class_name=nil,
   @counter_cache_column=nil,
   @foreign_key=nil,
   @inverse_of=nil,
   @inverse_which_updates_counter_cache=nil,
   @inverse_which_updates_counter_cache_defined=false,
   @join_table=nil,
   @klass=nil,
   @name=:workspace,
   @options={},
   @plural_name="workspaces",
   @scope=nil>}

参照

Active Record Reflection: reflections()