Option for Cascade Delete for References or On Delete

半城伤御伤魂 提交于 2019-12-02 20:21:55

This should work

create_table :childs do |t|
  t.references :parent, index: true, foreign_key: {on_delete: :cascade}
  t.string :name

  t.timestamps null: false
end

According to ActiveRecord::ConnectionAdapters::TableDefinition#references, if a hash is specified on the foreign_key option, it is directly passed down into the foreign_key method.

source:

foreign_key(col.to_s.pluralize, foreign_key_options.is_a?(Hash) ? foreign_key_options : {}) if foreign_key_options

Also note that if you already have the table setup, you can generate a migration to update the foreign_key by doing the following:

  def up
    remove_foreign_key :children, :parent
    add_foreign_key :children, :parent, on_delete: :cascade
  end

  def down
    remove_foreign_key :children, :parent
    add_foreign_key :children, :parent
  end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!