Home > Software engineering >  Rails method about foreign keys
Rails method about foreign keys

Time:07-07

I want to delete a company, but there is not dependent: destroy in the model. Is there an ActiveRecord method on Rails to know which tables are connected to a specific foreign key ?

CodePudding user response:

Using ActiveRecord::reflect_on_all_associations and Array#reject you can filter all has_many association without :dependent key

Company.
  reflect_on_all_associations(:has_many).
  reject { |association| association.options[:dependent] }

To get table names you can use plural_name attribute

Company.
  reflect_on_all_associations(:has_many).
  reject { |association| association.options[:dependent] }.
  map(&:plural_name)
  • Related