级联删除或参考删除选项 [英] Option for Cascade Delete for References or On Delete

查看:67
本文介绍了级联删除或参考删除选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails 4.2中,当创建表或通过引用或add_reference添加引用时,如何指定外键应在删除时级联。

In Rails 4.2, when creating a table or adding a reference via references or add_reference how do you specify that the foreign key should cascade on delete.

生成命令脚手架:

rails g scaffold Child parent:references name:string

结果迁移:

create_table :childs do |t|
  t.references :parent, index: true, foreign_key: true
  t.string :name

  t.timestamps null: false
end


推荐答案

这应该有效

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

  t.timestamps null: false
end

根据 ActiveRecord :: ConnectionAdapters :: TableDefinition#references ,如果在 foreign_key 选项上指定了哈希,则该哈希将直接传递到 foreign_key 方法中。

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.

源:

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

这篇关于级联删除或参考删除选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆