我可以在 Rails 中设置级联删除吗?

我知道这可能在互联网上的某个地方,但我在 Stackoverflow 上找不到答案,所以我想我可以在这里增加一点知识库。

我是 Ruby 和 Rails 的新手,但是我的公司已经在这方面投入了很多,所以我正在尝试了解更多的细节。

对我来说,很难改变我的思维模式,从“模型”而不是从数据库设计应用程序,所以我试图找出如何做所有的设计工作,我已经在数据库中的 Rails 模型,而不是经典的。

因此,我给自己的最新任务是弄清楚如何配置 Rails 数据库模型来执行级联删除?有什么简单的方法吗?或者我必须进入 MySql 并设置这个?

64609 次浏览

Yeah you can, if you are using a relationship like has_many you just do this

has_many :memberships, dependent: :destroy

It looks like this plugin might give you what you're looking for if you want the cascading deletes reflected in the actual database structure:

http://www.redhillonrails.org/foreign_key_migrations.html

Format for using this in a migration would be something like this:

create_table :orders do |t|
t.column :customer_id, :integer, :on_delete => :set_null, :on_update => :cascade
...
end

you can also set the :dependent option to :delete_all. :delete_all will issue a single SQL statement to delete all child records. because of this using :delete_all may give you better performance.

has_many :memberships, dependent: :delete_all

Just keep in mind that delete_all will not execute any callbacks (like before_destroy and after_destroy) on the child records.

Contrary to the provided answer I highly suggest also doing this on a database level. In case you have different processes or a multi threaded environment it could happen that records are not properly deleted. Furthermore the database foreign key makes things way faster when deleting lots of data.

Like in the suggested answer do this:

has_many :memberships, dependent: :delete_all

However also make sure to setup a foreign_key in a migration. That way the database takes care of deleting the records automatically for you.

To nullify the values when a membership is deleted, assuming you have a user model:

add_foreign_key :users, :memberships, on_delete: :nullify

You can also delete all the models whenever a membership is deleted

add_foreign_key :users, :memberships, on_delete: :cascade