I need to save a bunch of people that a related to a movie without duplication.
Let's take the movie Inglourious Basterds as an example.
Here Quentin Tarantino has a bunch of roles.
- Director
- Writer
- Actor
Here is an example of an rspec test
Movie.find_by开发者_JAVA百科_title("Inglourious Basterds").actors.map(&:name).should include("Quentin Tarantino")
Movie.find_by_title("Inglourious Basterds").writers.map(&:name).should include("Quentin Tarantino")
Movie.find_by_title("Inglourious Basterds").directors.map(&:name).should include("Quentin Tarantino")
How should I set up the relations between the models?
This is a fairly simple set of models for rails to do.
rails g model movie name:string
rails g model person name:string
rails g model movie_role movie:belongs_to person:belongs_to role:string
And for the model associations:
class Person < ActiveRecord::Base
has_many :movie_roles
has_many :movies, :through => :movie_roles
end
class Movie < ActiveRecord::Base
%w(actor director writer).each do |type|
base = "#{type}_movie_roles"
has_many base, :conditions => { :role => type }, :class_name => 'MovieRole'
has_many type.pluralize, :through => base, :source => :person
end
end
精彩评论