Rails 和参照完整性 [英] Rails and referential integrity

查看:53
本文介绍了Rails 和参照完整性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以编写迁移而不是以下原始 SQL 语句:

I would like to know if it's possible to write a migration instead of of the following raw SQL statement:

execute <<-SQL
  ALTER TABLE records
    ADD CONSTRAINT fk_records_domains
    FOREIGN KEY (domain_id)
    REFERENCES domains(id) ON DELETE CASCADE
SQL

我想避免使用 sql,因为我在尝试回滚此类迁移时遇到问题:

I would like avoid using sql because i'm getting problems when trying to rollback such migration:

execute <<-SQL
  ALTER TABLE records
    DROP FOREIGN KEY fk_records_categories
SQL





rake db:rollback
==  Integrity: reverting ======================================================
-- execute("      ALTER TABLE records\n        DROP FOREIGN KEY                                      fk_records_categories\n")
rake aborted!
An error has occurred, all later migrations canceled:

Mysql2::Error: Error on rename of './BlackshardDev/records' to './BlackshardDev/#sql2-44cc-16c' (errno: 152):       ALTER TABLE records
    DROP FOREIGN KEY fk_records_categories

我知道 activerecord 可以处理参照完整性,但我希望也能够用后端管理它.谢谢

I know that activerecord can handle the referential integrity but i would like to be able to manage it also with the backend. Thanks

推荐答案

根据 Rails 迁移指南:

Active Record 方法声称智能属于你的模型,而不是数据库.因此,触发器或外键约束等将某些智能推回数据库的功能并未被大量使用.

The Active Record way claims that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database, are not heavily used.

虽然 Active Record 没有提供任何直接使用这些特性的工具,但是 execute 方法可以用来执行任意 SQL.您还可以使用一些插件,如 foreigner 为 Active Record 添加外键支持(包括对转储外键的支持)在 db/schema.rb 中).

Although Active Record does not provide any tools for working directly with such features, the execute method can be used to execute arbitrary SQL. You could also use some plugin like foreigner which add foreign key support to Active Record (including support for dumping foreign keys in db/schema.rb).

Foreigner 的 add_foreign_keyremove_foreign_key 可能会满足您的要求,但我对此没有任何直接经验.

Foreigner's add_foreign_key and remove_foreign_key probably do what you're asking for, but I don't have any direct experience with it.

这篇关于Rails 和参照完整性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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