处理这个问题的最好方法是创建一个丰富的连接表。
即:
| 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
哦,伙计,没关系!导轨让我几乎每天都会感到惊奇......(好吧,我对它很陌生)感谢您的杰出答案,正是我一直在寻找的! – 2009-11-25 01:34:01
in class Movie你的意思是“has_many:people,:through =>:credits”而不是“has_many:people,:through =>:jobs”我是对吗? – 2009-11-25 01:36:41
是的,我把它写成了工作,然后意识到信用更有意义。所以我改变了它,一定错过了。对困惑感到抱歉。 – EmFi 2009-11-25 03:23:10