在 Rails 上创建表时需要创建外键吗?
我现在开始使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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.
在数据库中拥有外键有很多正当的理由。请参阅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.