Help with model! Do I need to use a model as a join table?


#1

HI all, newbie question, I’m not sure exactly how I should model the
following DB Structure, do I need to use a model as a join table? Here
is my database

actors

  • id
  • name
  • age

movie

  • id
  • name
  • year

role

  • id
  • name
  • requiresSwimming
  • requiresHorseskills

movie_actor

  • actor_id
  • movie_id
  • role_id

How should I map this in my model in rails? An actor can only have
one role in each movie.

class Role < ActiveRecord::Base
end

class Movie < ActiveRecord::Base
end

class Actor < ActiveRecord::Base
end

Thanks J


#2

Well, if each Role belongs to 1 specific movie and 1 actor, you don’t
even need the movie_actor table…
us a has_many :thorugh relationship, and roles as the join table…

actors

  • id
  • name
  • age

movie

  • id
  • name
  • year

role

  • id
  • movie_id
  • actor_id
  • name
  • requiresSwimming
  • requiresHorseskills

class Role < ActiveRecord::Base
belongs_to :movie
belongs_to :actor
end

class Movie < ActiveRecord::Base
has_many :roles
has_many :actors, :through => :roles
end

class Actor < ActiveRecord::Base
has_many :roles
has_many :movies, :through => :roles
end

@actor= Movie.find(1).roles[1].actor

find the actor who plays the first role in the first movie


#3

I can’t do that because the Roles are a standard set e.g.

Leading Man
Leading Lady

so although Tom Cruise can only be Leading Man once on Mission
Impossible, Tom can also be Leading man once on Mission Impossible 2

so I do need that actor_roles table

So how should I map that ?

J


#4

ah ok i get it. the attributes like “requires_horseskills” made it
look like indiviudal entries as opposed to a standard set.
well then do this:

actors

  • id
  • name
  • age

movie

  • id
  • name
  • year

role

  • id
  • name
  • requiresSwimming
  • requiresHorseskills

Appearance

  • id
  • movie_id
  • actor_id
  • role_id

class Role < ActiveRecord::Base
has_many :appearances
has_many :movies, :through => :appearances
has_many :actors, :through => :appearances
end

class Movie < ActiveRecord::Base
has_many :appearances
has_many :actors, :through => :appearances
has_many :roles, :through => :appearances
end

class Actor < ActiveRecord::Base
has_many :appearances
has_many :movies, :through => :appearances
has_many :roles, :through => :appearances

end

class Appearance < ActiveRecord::Base
belongs_to :movie
belongs_to :actor
belongs_to :role
end

… so now the Model Appearance is the center of the 3 others, and
each of those can find it’s corresponding items in the other 2
throught the appeances join table.


#5

Thanks I’ll try that