简体   繁体   English

我应该在Rails项目中以这种“ has_many:through”关系使用ENUM还是创建另一个数据透视表?

[英]Should I use an ENUM or create another pivot table in this “has_many :through” relationship in my Rails project?

I am beginner Rails developer trying to build an interface for a movie database. 我是Rails开发人员,试图为电影数据库建立接口。 I am in the middle of creating a "has_many :through" many-to-many relationship between a person model and a project model using a pivot table called "persons_projects". 我正在使用称为“ persons_projects”的数据透视表在人员模型和项目模型之间创建“ has_many:through”多对多关系。 This table currently has 2 columns: person_id and project_id. 该表当前有2列:person_id和project_id。 I want to add another column to indicate the role that the person is playing in the project (actor, director, etc). 我想添加另一列以指示该人在项目中扮演的角色(演员,导演等)。 Should I create a new table for the roles and add the new column as a foreign key in persons_projects as role_id or is this where I would use an ENUM with values such as "ACTOR", "DIRECTOR"? 我应该为角色创建一个新表并将新列作为person_projects中的外键添加为role_id还是在此处使用带有“ ACTOR”,“ DIRECTOR”等值的ENUM? I've never used ENUMs and was wondering if this is a good use case? 我从未使用过ENUM,并且想知道这是否是一个好用例?

Should I create a new table for the roles and add the new column as a foreign key in persons_projects as role_id? 我是否应该为角色创建一个新表,并将新列作为person_projects中的外键添加为role_id?

No, you shouldn't, because the number of roles is just a few, and stable. 不,您不应该这样做,因为角色的数量很少而且很稳定。 So it is inefficient to create a new table. 因此创建新表效率不高。

I would use an ENUM with values such as "ACTOR", "DIRECTOR"? 我会使用带有“ ACTOR”,“ DIRECTOR”等值的ENUM吗? I've never used ENUMs and was wondering if this is a good use case? 我从未使用过ENUM,并且想知道这是否是一个好用例?

Of course, this is absolutely the use case for using enum , you can do something like this: 当然,这绝对是使用enum的用例,您可以执行以下操作:

class PersonProject < ActiveRecord::Base
  belongs_to :person
  belongs_to :project
  enum role: [:actor, :director]
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM