处理这个问题的最好方法是创建一个丰富的连接表。
IE:
| has many => | | <= has many |
Person | | Credit | | Movie
| <= belongs to | | belongs to => |
Person 和 Movie 与最初的示例相比变化不大。Credit 包含的字段不仅仅是 person_id 和 movie_id。Credit 的额外字段将是角色和角色。
然后它只是一个有很多通过关系。但是,我们可以添加额外的关联来获得更多细节。以电影为例:
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
与所有这些额外的关联。以下每一项都只是一个 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