RoR定义了两个模型之间有意义的关系

Pat*_*ity 1 many-to-many ruby-on-rails has-many semantics

我想在rails项目中定义多对多关系.如何赋予个人关系不同的意义?

+------------+        has many        +-------------+
|            | ---------------------> |             |
|   person   |                        |   project   |
|            | <--------------------- |             |
+------------+        has many        +-------------+
Run Code Online (Sandbox Code Playgroud)

这个模型对于一个开始是好的,但对于我想要实现的目标来说还不够.一个人应该能够在一个项目中扮演不同的角色.例如在电影中有演员,制片人,特效家伙......

解决方案应该......

  • 提供一种简单的方法来定义新的关系类型('角色')
  • 以一种很好的方式集成到rails中
  • 尽可能快

什么是最好的选择?

EmF*_*mFi 7

最好的方法是处理这个是创建一个丰富的连接表.

即:

       |  has many =>  |        |  <= has many  |
Person |               | Credit |               | Movie
       | <= belongs to |        | belongs to => |
Run Code Online (Sandbox Code Playgroud)

人物和电影在最初的例子中没有太大变化.而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
Run Code Online (Sandbox Code Playgroud)

与所有这些额外的关联.以下每个只有一个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
Run Code Online (Sandbox Code Playgroud)