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 4.2中,当创建一个表或通过引用或add_reference添加引用时,您如何指定外键应该在删除时级联。
Command to generate scaffold:
命令生成脚手架:
rails g scaffold Child parent:references name:string
Resulting migration:
导致的迁移:
create_table :childs do |t|
t.references :parent, index: true, foreign_key: true
t.string :name
t.timestamps null: false
end
1 个解决方案
#1
35
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.
根据ActiveRecord:: connectionadapter::TableDefinition#引用,如果在foreign_key选项中指定了一个散列,它将直接传递给foreign_key方法。
source:
来源:
foreign_key(col.to_s.pluralize, foreign_key_options.is_a?(Hash) ? foreign_key_options : {}) if foreign_key_options
#1
35
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.
根据ActiveRecord:: connectionadapter::TableDefinition#引用,如果在foreign_key选项中指定了一个散列,它将直接传递给foreign_key方法。
source:
来源:
foreign_key(col.to_s.pluralize, foreign_key_options.is_a?(Hash) ? foreign_key_options : {}) if foreign_key_options