CubicLouve

Spring_MTの技術ブログ

railsで特定のモデルに対してbelongs_toで参照先を設定しているモデルを取り出す

まあ、いろいろ調べる必要がありまして。。。

ざっくりとこんな感じでとれた。

# production環境では要らないが、development環境では必要かと
Dir.glob(File.expand_path('./app/models/*.rb', Rails.root)).each do |f|
  require f
end

# 定数を全部取得
constants = Object.constants.map do |name|
  Object.const_get(name)
end

# 定数一覧からモデルを絞り込む
all_models = constants.select do |c|
  c.class == Class && c < ActiveRecord::Base && !c.abstract_class?
end
                                                                                                                          
target = {}
all_models.each do |model|
  model.reflect_on_all_associations(:belongs_to).each do |association|
    if association.name == :hoge || %w(Hoge).include?(association.options[:class_name])
      target[association.active_record.name] = { model: association.active_record, foreign_key: association.foreign_key }
    end
  end
end
target

これで対象モデルが取得できたのであとはよしなに使う。 例えば、一つも参照がされていないデータを取ってくるとか。

target_ids = Hoge.pluck(:id)

target.each do |name, modle|
  used_ids = model[:model].where(model[:foreign_key] => target_ids).pluck(:"#{model[:foreign_key]}")
  target_ids -= used_ids
end
target_ids

とか