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

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

问题描述

我现在开始在Rails上,我在论坛上,但我没有找到任何可以解决我的问题。

在这里,我有一个分类表,它只有一个列的名称(没有类别的重复),所以我想名字是主关键,那么我有一个产品表,有名称,main_photo,说明,我想说,一个产品只有一个类别,我需要添加一个名为类的列作为产品的外键?

一个类别有许多产品。然后在类别模型中,我怎么说名字是主键,我怎样才能做出产品类别和类别中的主键名称之间的对应关系? Active Record中的外键约束并不经常被使用,因为Active Record背后的意识形态认为这种逻辑应该属于模型而不是数据库 - 数据库只是一个愚蠢的存储: http: //guides.rubyonrails.org/migrations.html#active-record-and-referential-integrity

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



然后在您的模型中定义实体Product和Category之间的关系。阅读文章 活动记录协会指南 ,它会回答你所有的问题,尤其是2.1,2.2和3.3。

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?

解决方案

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上创建表时需要创建一个外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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