问题
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.
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:
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
回答2:
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
来源:https://stackoverflow.com/questions/30154798/option-for-cascade-delete-for-references-or-on-delete