我什么时候应该使用“NOT NULL” 在 MySQL 表中有什么好处吗?

发布于 2024-07-08 03:35:54 字数 557 浏览 6 评论 0原文

我有以下 Rails 迁移:

create_table :articles do |t|
  t.integer :user_id, :allow_null => false
  t.integer :genre_id, :allow_null => false
  t.string :url, :limit => 255, :allow_null => false
  t.string :title, :limit => 60, :allow_null => false
  t.text :summary, :limit => 350, :allow_null => false
  t.integer :votes_count, :default => 0
  t.datetime :published_at, :default => nil
  t.timestamps
end

首先在模型中验证所有“NOT NULL”字段,所以我想知道是否需要在迁移中麻烦地使用allow_null? 我不确定“NOT NULL”会给数据库带来什么好处(如果有的话)。

I have the following rails migration:

create_table :articles do |t|
  t.integer :user_id, :allow_null => false
  t.integer :genre_id, :allow_null => false
  t.string :url, :limit => 255, :allow_null => false
  t.string :title, :limit => 60, :allow_null => false
  t.text :summary, :limit => 350, :allow_null => false
  t.integer :votes_count, :default => 0
  t.datetime :published_at, :default => nil
  t.timestamps
end

All the fields that are "NOT NULL" are validated in the model first, so I'm wondering if I need to bother having allow_null in the migration? I'm not sure what benefits "NOT NULL" gives to the database, if any.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不知所踪 2024-07-15 03:35:54

如果您指的是性能或存储效率,那就没什么了不起。 然而,将尽可能多的低级约束推入数据库层是一个很好的做法。 一方面,它保证 Rails 中的细微错误不会导致非空字段中出现一些随机的 NULL 数据。 同样,如果您曾经针对同一数据库运行另一个应用程序,那么将约束放在中心位置以进行维护并避免重复将非常有帮助。

Not much if you mean in terms of performance or storage efficiency. However, it's just good practice to push as many of your low-level constraints into the database layer. For one thing, it guarantees that a subtle bug in Rails isn't going to lead to some randomly NULL data in a not-null field. Likewise, if you ever run another app against the same database, it will be extremely helpful to have the constraints in a central place for maintenance and to avoid duplication.

眼眸里的快感 2024-07-15 03:35:54

NOT NULL 是计算机可以监视您并防止您犯错误的另一件事。

NOT NULL is one more thing where the computer can keep an eye on you and keep you from making mistakes.

酒几许 2024-07-15 03:35:54

This doesn't seemt o affect mySQL, but you should be aware of 2 recently fixed migration issues (one when you don't specify default)

http://blog.codefront.net/2008/05/04/living-on-the-edge-of-rails-19-change_table-for-migrations-and-more/

http://antoniocangiano.com/2008/07/14/a-close-look-at-three-rails-21-bugs/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文