Steph
Steph

Reputation: 27

Rails method about foreign keys

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 ?

Upvotes: 1

Views: 246

Answers (1)

mechnicov
mechnicov

Reputation: 15248

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)

Upvotes: 2

Related Questions