Rails(或 ActiveRecord)只是一个围绕数据库条目的简单 ORM。它没有利用数据库提供的大多数功能。部分原因是他们希望与 DB 无关,并且许多更高级的功能是 DBM 特定的。但也因为有些人认为将逻辑放入 DB 是万恶之源。
这并不意味着一切都是邪恶的,而是应该小心使用。尤其是存储过程。也就是说,我相信,外键约束和索引在 Rails 中没有得到充分利用。创建它们没有太多缺点(除了播种)。
例如,您可以在独一关系上使用唯一键约束来防止多条记录。 Rails 默认不这样做。您可以依赖验证,但使用数据库是更安全的选择:
add_index :child_table, [:parent_id], unique: true
您也可以利用外键约束自动让数据库删除依赖记录:
add_foreign_key :children, :parents, column: :parent_id, dependent: :delete
您可以将两者结合起来:
add_foreign_key :children, :parents, column: :parent_id, dependent: :delete, index: { unique: true }
还有很多方法可以利用 DB 来确保数据的完整性和一致性。
如果您现在使用引用创建 Rails 迁移,它实际上会为您创建索引和外键约束:
~blog $ rails g model Post author:references title:string content:text
Running via Spring preloader in process 33539
invoke active_record
create db/migrate/20160308141214_create_posts.rb
create app/models/post.rb
invoke test_unit
create test/models/post_test.rb
create test/fixtures/posts.yml
~/blog $ cat db/migrate/20160308141214_create_posts.rb
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.references :author, index: true, foreign_key: true
t.string :title
t.text :content
t.timestamps null: false
end
end
end