Rails中有不同的可能性将模型和表链接在一起。
add_column :books, :user_id, :integer, index: true
add_reference :books, :user, index: true, foreign_key: true
据我所知,我发现有些数据库对此选项有不同的行为。
我有兴趣找到采用表演和代码可读性的最佳做法。
我长时间使用整数索引列,我想知道是否应该使用foreign_keys引用。
更新:例如
在一个全新的测试应用程序中我运行:
rails g model book author_id:integer:index user:references
迁移文件如下所示:
class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.integer :author_id
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
add_index :books, :author_id
end
end
表格的ddl
- 表:public.books
-- DROP TABLE public.books;
CREATE TABLE public.books
(
id integer NOT NULL DEFAULT nextval('books_id_seq'::regclass),
author_id integer,
user_id integer,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
CONSTRAINT books_pkey PRIMARY KEY (id),
CONSTRAINT fk_rails_bc582ddd02 FOREIGN KEY (user_id)
REFERENCES public.users (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.books
OWNER TO my_user_name;
-- Index: public.index_books_on_author_id
-- DROP INDEX public.index_books_on_author_id;
CREATE INDEX index_books_on_author_id
ON public.books
USING btree
(author_id);
-- Index: public.index_books_on_user_id
-- DROP INDEX public.index_books_on_user_id;
CREATE INDEX index_books_on_user_id
ON public.books
USING btree
(user_id);
编辑2:这是一个描述问题的链接,并指出foreign_keys的重要性
答案 0 :(得分:1)
扩展我的评论:是的,外键的主要功能是保持参照完整性(https://en.wikipedia.org/wiki/Referential_integrity)。
作为附带好处,它们提供了有关模式的更明确的信息:查询和设计工具可以利用这些关系,而不是依赖于共享列名。
检查外键引用的所有列是否已编入索引也很容易,否则您只能在查询时发现缺少的索引。
http://www.postgresql.org/docs/current/static/ddl-constraints.html#DDL-CONSTRAINTS-FK
性能影响非常容易理解:只要子表中的数据发生更改(插入/删除/更新),您就会对父表执行索引查找。对于大多数中小型桌子,您永远不必担心它。