[英]RoR define meaningful relations between two models
我想在Rails項目中定義多對多關系。 賦予個人關系不同含義的最佳方法是什么?
+------------+ has many +-------------+
| | ---------------------> | |
| person | | project |
| | <--------------------- | |
+------------+ has many +-------------+
這個模型對於一個開始是很好的,但是對於我想要實現的目標是不夠的。 一個人應該能夠在項目中扮演不同的角色。 例如,電影中有演員,制片人,特技演員,...
解決方案應該...
最好的選擇是什么?
最好的方法是創建一個豐富的聯接表。
即:
| has many => | | <= has many |
Person | | Credit | | Movie
| <= belongs to | | belongs to => |
與最初的示例相比,“人物”和“電影”沒有太大變化。 信用不僅包含person_id和movie_id,還包含更多字段。 信用的額外字段將是角色和角色。
然后,這只是一個具有許多直通關系的關系。 但是,我們可以添加額外的關聯以獲取更多詳細信息。 與電影示例保持一致:
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
人員,項目和角色之間的關系應該是自己的表格。 制作一個具有一個人,一個項目以及該人在該項目中的角色的工作分配類。 然后Person has_many :projects, :through => :assignments
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.