ruby 关于外键的Rails方法

wwwo4jvm  于 2023-10-17  发布在  Ruby
关注(0)|答案(1)|浏览(115)

我想删除一个公司,但没有依赖:摧毁模型。Rails上是否有ActiveRecord方法来知道哪些表连接到特定的外键?

yfwxisqw

yfwxisqw1#

使用ActiveRecord::reflect_on_all_associations和Array#reject,可以过滤所有没有:dependent键的has_many关联

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

要获取表名,可以使用plural_name属性

  1. Company.
  2. reflect_on_all_associations(:has_many).
  3. reject { |association| association.options[:dependent] }.
  4. map(&:plural_name)

相关问题