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

时间:2009-11-25 00:58:30

标签: ruby-on-rails many-to-many has-many semantics

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

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

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

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

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

最佳选择是什么?

2 个答案:

答案 0 :(得分:7)

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

即:

       |  has many =>  |        |  <= has many  |
Person |               | Credit |               | Movie
       | <= belongs to |        | belongs to => |

在最初的例子中,人物和电影的变化不大。而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

答案 1 :(得分:1)

人,项目和角色之间的关系应该是一个独立的表。创建一个具有人员,项目和该人员在该项目中的角色的作业。然后是人has_many :projects, :through => :assignments