Rails 3 中的外键 [英] Foreign keys in Rails 3

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

问题描述

我明白,根据 Rails 的理念,数据完整性检查应该在应用程序级别而不是数据库级别进行.和许多其他开发者一样,我强烈反对.

I understand that according to Rails philosophy, data integrity checks should be done at the application level as opposed to the database level. Like many other developers, I enthusiastically disagree.

我发现很多讨论都在讨论这个问题,但它们似乎都过时了,而且令人沮丧的是,它们似乎指向了不同的解决方案.

I've found a lot of discussions addressing this problem but they all seem to be old and, dismayingly, they seem to point to divergent solutions.

我不得不想象在 Rails 3 中有一种事实上的标准方法来做外键约束.然而,无论它是什么(如果它确实存在)似乎都被过去的所有讨论所淹没,因为我找不到它.

I have to imagine there's a de-facto standard way of doing foreign key constraints in Rails 3. However, whatever it is (if it does exist) seems to be smothered by all the past discussions because I can't find it.

此时 Rails 开发人员是否大部分都在使用外键的同一页面上?如果是这样,我很想知道他们通常是如何处理的.

Are Rails developers by this point mostly on the same page with foreign keys? If so, I would love to know how they're generally handled.

推荐答案

正是因为这个原因,我(以及编写 Enterprise Rails 的人 - http://oreilly.com/catalog/9780596515201) 建议您使用 SQL 编写整个向上和向下迁移.

It is for this reason that I (and the people who wrote Enterprise Rails - http://oreilly.com/catalog/9780596515201) recommend that you write your entire up and down migrations in SQL.

优点是:

  • 能够在创建表时添加外键 - 无需单独的更改表
  • 它允许您使用特定于数据库的字段类型 - 如 tsvectors
  • 它允许您添加不同类型的索引 - 如 Gin 或 Gist
  • 它允许您编写函数和/或触发器
  • 您不必记住什么 DSL 类型与什么 SQL 字段类型相关 - 例如:数

有缺点:

  • 这与数据库无关(谁在乎您更改数据库的频率?)
  • 它不是 Ruby(但每个优秀的 Rails 开发人员都应该了解 SQL,对吗?)

但是,总的来说,我认为优点大于缺点.

But, overall I reckon the advantages outweigh the disadvantages.

快速示例:

  def self.up
    execute <<EOS

create table .... (
  ....
);

EOS
   end

这篇关于Rails 3 中的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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