我什么时候应该使用“NOT NULL” 在 MySQL 表中有什么好处吗?
我有以下 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您指的是性能或存储效率,那就没什么了不起。 然而,将尽可能多的低级约束推入数据库层是一个很好的做法。 一方面,它保证 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.NOT NULL 是计算机可以监视您并防止您犯错误的另一件事。
NOT NULL is one more thing where the computer can keep an eye on you and keep you from making mistakes.
这似乎不会影响 mySQL,但您应该注意 2 个最近修复的迁移问题(一个当您未指定默认值时)
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/
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/