0

I am beginner Rails developer trying to build an interface for a movie database. 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". This table currently has 2 columns: person_id and 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"? I've never used ENUMs and was wondering if this is a good use case?

soultrust
  • 581
  • 1
  • 7
  • 17

1 Answers1

0

Should I create a new table for the roles and add the new column as a foreign key in persons_projects as 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"? I've never used ENUMs and was wondering if this is a good use case?

Of course, this is absolutely the use case for using enum, you can do something like this:

class PersonProject < ActiveRecord::Base
  belongs_to :person
  belongs_to :project
  enum role: [:actor, :director]
end
Hieu Pham
  • 6,577
  • 2
  • 30
  • 50
  • Is it true that the Rails implementation of enum saves as an integer in the database as opposed to the enum datatype? If so, do you know of a way (maybe a gem?) to get around this? – soultrust Jan 20 '16 at 17:17
  • In deep, the datatype in database is integer, in above code, the role is `:actor` if it is `0` in database, if you define like this `enum role: {actor: 0, director: 1}` it will be clearer, this is for detail http://api.rubyonrails.org/v4.1/classes/ActiveRecord/Enum.html – Hieu Pham Jan 20 '16 at 17:37
  • Please check this thread http://stackoverflow.com/questions/25570209/how-get-integer-value-from-a-enum-in-rails – Hieu Pham Apr 17 '16 at 18:36