0

以下三種模型連接的最佳方式是什麼?2到1 has_many通過Rails中的關係(如何將三個模型連接在一起)

class Tournament < ActiveRecord::Base 
    has_many :submissions 
    has_many :creatures, :through => :submissions, :uniq => true 
    has_many :teams, :through => :submissions, :uniq => true 
end 

class Creature < ActiveRecord::Base 
    belongs_to :team 
    has_many :tournaments, :through => :team 
end 

class Submission < ActiveRecord::Base 
    belongs_to :tournament 
    belongs_to :team 
end 

class Team < ActiveRecord::Base 
    has_many :creatures 
    has_many :submissions 
    has_many :tournaments, :through => :submissions 
end 

我要實現的是這樣的:

> team_1.tournaments[0] = tournament_1 

> tournament_1.teams[0] 
(returns team_1) 

> team_1.tournaments[0].creatures 
(returns []) 

> team.tournaments[0].creatures[0] = creature_1 

> creature_1.tournaments 
(returns tournament_1) 

什麼是有一個特定的生物,與特定的比賽相關的團隊最有效的方法是什麼?

編輯:上面是期望的行爲..目前的問題是,只要我將隊伍添加到tournament.teams該團隊中的所有生物自動將該比賽列在creature.tournament中,而我試圖讓它使生物被選擇性地添加到比賽中。是否可以用一個連接表?

謝謝!

回答

0

提交應該是您的連接表TournamentsTeams之間的連接表,對嗎?

   Creature [id, team_id] 
          | 
          | 
          | 
         Team [id] 
          | 
          | 
          | 
      Submission [id, team_id, tournament_id] 
              | 
              | 
              | 
           Tournament [id] 

模型關係:

class Creature < ActiveRecord::Base 
    belongs_to :team 
    has_many :tournaments, :through => :team # this should work since Rails 3.1 or 3.2 
end 

class Team < ActiveRecord::Base 
    has_many :creatures 
    has_many :tournaments, :through => :submissions 
    has_many :submissions 
end 

class Submission < ActiveRecord::Base 
    belongs_to :team 
    belongs_to :tournament 
end 

class Tournament < ActiveRecord::Base 
    has_many :teams, :through => :submissions 
    has_many :creatures, :through => :teams  # this should work since Rails 3.1 or 3.2 
    has_many :submissions 
end 

現在,你應該能夠調用: team_1.tournaments[0].creatures

+0

完全不是那麼回事,我(的Rails 3.1.3):當我做team_1.tournaments [ 0]。生物我得到該團隊的所有生物都返回了,而我只需要獲得那些提交給那個比賽的生物......另外我不能調用creature.tourmanents(返回:找不到關聯:模型生物中的團隊)。 – Stpn 2012-01-04 18:00:28

+0

哦修復後者應該是:通過=>:團隊而不是teamS(我修正了上面的問題!)。那樣有用嗎? – 2012-01-05 10:55:07

相關問題