1

我想在 Rails 项目中定义多对多关系。赋予个体关系不同含义的最佳方式是什么?

+------------+        has many        +-------------+
|            | ---------------------> |             |
|   person   |                        |   project   |
|            | <--------------------- |             |
+------------+        has many        +-------------+

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

解决方案应该...

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

什么是最好的选择?

4

2 回答 2

7

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

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
于 2009-11-25T01:18:59.323 回答
1

人、项目和角色之间的关系应该是一张自己的表。创建一个包含一个人、一个项目以及该人在该项目中的角色的 Assignment 类。然后人has_many :projects, :through => :assignments

于 2009-11-25T01:07:06.207 回答