2013-03-08 100 views
1

我有一個Play有很多CostumedActors。 CostumeActor是一個演員和服裝的聯合,它們之間有多對多的關係。has_many:通過,3路加入

這似乎是一個模式,應該是相當普遍的,但我不清楚在軌道中做到這一點的最佳方式。

我現在已經將其設置爲3路連接關聯如下:

class Play < ActiveRecord::Base 
    has_many :costumed_actors 
    has_many :actors, :through => costumed_actors 
    has_many :costumes,:through => costumed_actors 
end 

class CostumedActor < ActiveRecord::Base 
    belongs_to :play 
    belongs_to :costume 
    belongs_to :actor 
end 

class Costume < ActiveRecord::Base 
    has_many :actors, :through => costumed_actors 
    has_many :plays, :through => costumed_actors 
end 

class Actor < ActiveRecord::Base 
    has_many :costumes, :through => costumed_actors 
    has_many :plays, :through => costumed_actors 
end 

Rails沒有完全處理這個問題。如果我想看一齣戲的演員或服飾,沒有問題:

play.costumes 
play.actors 

但是,如果我想看到的演員穿着古裝哪,我不能做

play.actors.costumes 

在這種情況下, .costumes給了我所有演員穿戴的所有服裝,不僅僅是現在的服裝。

我必須做的是這樣的:通過增加一個輔助方法給的has_many

play.costumed_actors.where(:actor => @actor).map {|x| x.costumes} 

或更乾淨,:通過關聯

class Play 
    has_many :costumes, :through => costumed_actors do 
    def for_actor(actor) 
     where("costumed_actors.actor_id = ?", actor) if !actor.nil? 
    end 
    end 
end 

play.costumes.for_actor(@actor) 

而且,加入協會工作不正常。我想能夠做一些像

Play.actors << actor.with_costume(costume) 

但我看不出如何階段關聯輔助方法,或者即使這種方法是可能的。

這是表示這種情況的最佳方式嗎?如果是這樣的話,這是讀取/寫入關聯記錄的最佳方式嗎?

回答

0

試試這個:

class Play 
    has_many :actors_costumes, :through => :actors, :source => :costumes 
end 

你可以得到演員的服裝如下:

play.actors_costumes 
+0

謝謝,但是這似乎產生完全相同的SQL作爲一個簡單的'play.actors'有3關係,對於這種查詢,我需要以某種方式指定其中的2個,並獲得第三個,如我的示例'play.actors.with_costume(costume)'。我的一個更大的問題是關於在軌道中使用3表連接表示的正確方法(可能更準確地將其描述爲帶有查詢表的許多元素) – jackpipe 2013-03-08 08:34:57