0

다음 세 모델을 연결하는 가장 좋은 방법은 무엇입니까?레일스에서 ​​2 대 1 has_many through 관계 (세 모델을 함께 연결하는 방법)

> 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) 

특정 생물 및 특정 대회와 관련된 팀을 보유하는 가장 효율적인 방법은 무엇입니까 :

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 

나는 이런 식으로 뭔가를 달성하려면?

EDIT : 위의 동작은 .. 현재 문제는 내가 팀을 토너먼트에 추가하자마자 그 팀의 모든 생명체가 자동으로 해당 토너먼트를 생물체에 표시한다는 것입니다. 생물이 선택적으로 토너먼트에 추가되도록 .. 하나의 조인 테이블에서 가능합니까?

감사합니다.

답변

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

나 (레일 3.1.3)에 대한 꽤 작동합니까 : 나는 team_1.tournaments는 [수행 할 때 0] .creatures 나는 그 팀의 모든 생명체를 돌려 주었고, 그 대회에 제출 된 사람들 만 얻을 필요가있다 ... 또한 생물체를 호출 할 수 없다. 반환 자 : 협회를 찾을 수 없었다 :). – Stpn

+0

아, 후자를 수정하려면 다음을 수행해야합니다. through => : 팀이 아닌 팀 (위의 내용을 수정했습니다!). 그게 효과가 있니? –

관련 문제