2009-11-25 132 views
1

我想定义一个rails项目中的多对多关系。如何给个人关系提供不同的意义?RoR定义两个模型之间的有意义的关系

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

这种模式是一个好的开始,但不足以实现我的目标。一个人应该能够在一个项目中扮演不同的角色。例如在电影中还有演员,制片人,特技人,...

溶液应...

  • 提供了一种简单的方法来定义新类型的关系(“角色”)
  • 纳入轨道在一个不错的方式
  • 是尽可能快地

什么是最好的选择吗?

回答

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 
+0

哦,伙计,没关系!导轨让我几乎每天都会感到惊奇......(好吧,我对它很陌生)感谢您的杰出答案,正是我一直在寻找的! – 2009-11-25 01:34:01

+0

in class Movie你的意思是“has_many:people,:through =>:credits”而不是“has_many:people,:through =>:jobs”我是对吗? – 2009-11-25 01:36:41

+0

是的,我把它写成了工作,然后意识到信用更有意义。所以我改变了它,一定错过了。对困惑感到抱歉。 – EmFi 2009-11-25 03:23:10

1

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

+0

感谢您的回答!你有什么流行语给我,这样我可以阅读更多关于这个话题?会很棒,我对这一切仍然很不安全。 – 2009-11-25 01:24:44

+0

我推荐阅读Rails协会指南:http://guides.rubyonrails.org/association_basics.html – 2009-11-25 23:45:31

相关问题