これを処理する最善の方法は、豊富な結合テーブルを作成することです。
すなわち:
| has many => | | <= has many |
Person | | Credit | | Movie
| <= belongs to | | belongs to => |
Person と Movie は、最初の例からあまり変わりません。また、Credit には person_id と movie_id 以外のフィールドが含まれています。クレジットの追加フィールドは、役割とキャラクターです。
それから、それは単に多くの関係を持っています。ただし、関連付けを追加して詳細を取得できます。映画の例を維持する:
class Person < ActiveRecord::Base
has_many :credits
has_many :movies, :through => :credits, :unique => true
has_many :acting_credits, :class_name => "Credit",
:condition => "role = 'Actor'"
has_many :acting_projects, :class_name => "Movie",
:through => :acting_credits
has_many :writing_credits, :class_name => "Credit",
:condition => "role = 'Writer'"
has_many :writing_projects, :class_name => "Movie",
:through => :writing_credits
end
class Credit < ActiveRecord::Base
belongs_to :person
belongs_to :movie
end
class Movie < ActiveRecord::Base
has_many :credits
has_many :people, :through => :credits, :unique => true
has_many :acting_credits, :class_name => "Credit",
:condition => "role = 'Actor'"
has_many :actors, :class_name => "Person", :through => :acting_credits
has_many :writing_credits, :class_name => "Credit",
:condition => "role = 'Writer'"
has_many :writers, :class_name => "Person", :through => :writing_credits
end
これらすべての追加の関連付けを使用して。次のそれぞれは、1 つのみの SQL クエリです。
@movie.actors # => People who acted in @movie
@movie.writers # => People who wrote the script for @movie
@person.movies # => All Movies @person was involved with
@person.acting_projects # => All Movies that @person acted in