[英]Do I really need to create intermediate SQL tables if I use active record with ruby on rails?
I read a book and I from what I've seen I can't even think of one case that justifies using an intermediate SQL table to relate ID's as I was thought in University a good database design should have...the model specifies that kind of relations. 我读了一本书,从我所看到的结果中,我什至无法想到一个案例,该案例证明使用中间SQL表来关联ID是合理的,正如我在大学中认为的那样,一个好的数据库设计应该具有...该模型指定一种关系。 I come fdrom the raw SQL world and now that I've discovered active record I don't see the need for relating id's on tables anymore. 我来自原始SQL世界,现在我发现了活动记录,所以我不再需要在表上关联id了。 Am I wrong on this one?. 我错了吗? If I am, please, enlighten me on why should I keep creating those intermediate SQL tables... 如果我愿意,请启发我为什么要继续创建那些中间SQL表...
Intermediate tables -- such as those with only foreign keys in them -- are necessary for many-to-many associations. 中间表(例如其中仅包含外键的表)对于多对多关联是必需的。 For instance if you have a relationship between students and classes in which a student can belong to multiple classes and classes can have multiple students, then you'll need such a join table. 例如,如果您在学生和班级之间存在某种关系,其中一个学生可以属于多个班级,而一个班级可以有多个学生,那么您将需要这样的联接表。
This is inherent in the relational database architecture, and is not changed by adding ActiveRecord to the mix. 这在关系数据库体系结构中是固有的,并且不会通过将ActiveRecord添加到组合中来更改。 ActiveRecord can make it easy to ignore such intermediate tables when writing queries, but it needs to include them when building queries. ActiveRecord可以使编写查询时忽略这些中间表变得容易,但是在构建查询时需要将它们包括在内。
Consider how you would associate many students to classes that in turn have many students, without a join table. 考虑一下如何将许多学生与班级联系起来,而班级又有很多学生,而又没有联接表。 Either each student record would have to have multiple columns containing foreign keys to different classes, or multiple student records with the same data, but different foreign keys of a class would be needed. 每个学生记录将必须具有包含不同类外键的多列,或者具有相同数据的多个学生记录,但是将需要一个类的不同外键。 The first method would limit the number of associations to the number of foreign key columns. 第一种方法是将关联数限制为外键列数。 The second method would break the normalization of the database by storing the same data in multiple records. 第二种方法是通过将相同的数据存储在多个记录中来破坏数据库的规范化。
By creating a join table instead, a student <-> class association can be recorded by simply adding a record to the join table. 通过创建联接表,只需将记录添加到联接表即可记录学生<->班级关联。 Any number of these associations can be created (up to the db table size limitation), and no data need be repeated. 可以创建任意数量的这些关联(不超过db表大小限制),并且不需要重复数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.