在 Rails 上创建表时需要创建外键吗?

发布于 2024-12-19 01:58:54 字数 238 浏览 2 评论 0原文

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

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

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

那么在类别模型中如何说名称是主键,以及如何将类别中的假定主键名称与产品中的类别进行对应?

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

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.

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?

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

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

发布评论

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

评论(2

冷情妓 2024-12-26 01:58:54

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

Rails 的方法是在所有表(包括“类别”表)上都有一个 ID 列,并在“产品”表中有一列名为“Category_ID”的列。请注意,表名是复数。

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

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.

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.

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.

懵少女 2024-12-26 01:58:54

在数据库中拥有外键有很多正当的理由。请参阅Rails 需要数据库级约束吗?

我建议 < a href="https://github.com/matthuhiggins/foreigner" rel="nofollow noreferrer">外国人 如果你愿意轻松地将外键添加到您的 Rails 应用程序中。

There are many valid reasons to have foreign keys in your database. See Does Rails need database-level constraints?

I recommend Foreigner if you want to easily add foreign keys to your Rails app.

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