samedi 25 avril 2015

has_many through roles and scopes on the third model


Lets say I have movies, people and movies_people

class Person < ActiveRecord::Base
  has_many :movies_people
  has_many :movies, through: :movies_people

class Movies < ActiveRecord::Base
  has_many :movies_people
  has_many :people, through: :movies_people


class MoviesPerson < ActiveRecord::Base
  belongs_to :movie
  belongs_to :person
end

The table movies_people has a role attribute, where I want to store the person's job in the movie. Right now I can do things like this in the console:

u = User.first
m = Movie.first
m.people << u

then find the right movies_people entry and set 'role'

retrieving looks like this:

m.people.where(movies_people: {role: :actor})


Whats the best way to:

  1. Save the role (to the third table) when joining people to movies?
  2. Return all the actors in a movie vs. all the directors vs. all the writers?

Aucun commentaire:

Enregistrer un commentaire