在 Rails 上创建表时需要创建外键吗? [英] Need to create a foreign key when creating a table on Rails?

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

问题描述

我现在开始使用 Rails,我查看了论坛,但我没有找到任何可以解决我的问题的东西.

i'm starting now on Rails, i looked in the forum, but i didn't find anything that could solve my problem.

在这里,我有一个 Category 表,它只有一个列的名称(类别中没有重复)所以我希望 name 作为主键,然后我有一个 Product 表,它有 name,main_photo,description,我想说一个产品只有一个类别,我是否需要在产品中添加一个名为 category 的列作为外键?

Here it goes, I have a Category table, and it has only name for a column (there is no repetition in categories) so i would like name to be the primary key, then i have a Product table that has name, main_photo, description and i would like to say that a product only has a category, do i need to add a column named category as a foreign key in products?

一个类别应该有很多产品.

A Category is suposed to have many products.

那么在category模型中怎么说name是primary Key,在category中假设的主键名称和products中的category如何对应呢?

Then in category models how do i say that name is the primary Key, and how can i do the correspondence between the suposed primary key name in categories and category in products?

推荐答案

Active Record 中的外键约束并不经常使用,因为 Active Record 背后的意识形态认为这种逻辑应该属于模型而不是数据库 - 数据库只是一个愚蠢的存储:http://guides.rubyonrails.org/migrations.html#active-record-and-referential-integrity.

Foreign key constraints in Active Record aren't used very often as the ideology behind Active Record says that this kind of logic should belong in the model and not in the database - the database is just a dumb store: http://guides.rubyonrails.org/migrations.html#active-record-and-referential-integrity.

Rails 方法是在所有表(包括 Categories 表)上都有一个 ID 列,在 Products 表中,有一个名为 Category_ID 的列.请注意,表名是复数形式.

The Rails way is to have an ID column on all tables including your Categories table, and in your Products table, have a column called Category_ID. Notice that the table names are plurals.

然后在您的模型中定义实体产品和类别之间的关系.阅读文章 Active Record 关联指南,它将回答您的所有问题,尤其是部分2.1、2.2 和 3.3.

Then in your model you define the relationships between the entities Product and Category. Read the article A Guide to Active Record Associations and it will answer all your questions, especially sections 2.1, 2.2 and 3.3.

这篇关于在 Rails 上创建表时需要创建外键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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