2013-11-14 3 views
3

나는 기본적인 연결이 될 것이라고 생각하는 것에 문제가 있습니다.레일 연결 - has_many 대 has_and_belongs_to_many

저는 게임 모델과 Matchset 모델을 가지고 있습니다.

게임 모델에는 게임 목록이 있습니다. 게임은 게임 테이블에 한 번만 나열되지만 많은 Matchsets에 속할 수 있습니다.

matchset.rb - game.rb에 대한

has_many :games 

은 내가 넣어 될지 모르겠어요. 나는 belongs_to를 넣고 싶지 않습니다. 왜냐하면 그것은 하나뿐 아니라 많은 matchset에 속하기 때문입니다. 그리고 matchsets가 반드시 게임에 속해서는 안되기 때문에 has_and_belongs_to_many를 넣고 싶지 않다고 생각합니다. 그러나 아마도 나는 잘못보고 있습니다.

예 : Matchset 1 게임 1, 3이 있고, 5 Matchset이 게임을 가지고 2, 3 Matchset 3 게임 3, 4를 가지고 있으며, 오라클 SQL과에서 내 머리에 5

내 배경 Matchset 테이블은 다음과 같이 보입니다.

id | game_id 
1 | 1 
1 | 3 
1 | 5 
2 | 2 
2 | 3 
3 | 3 
3 | 4 
3 | 5 

도움을 주시면 감사하겠습니다.

답변

2

이 관계는 당신을 위해 일해야합니다

class Game < ActiveRecord::Base 
    has_many :game_match_set_relations 
    has_many :match_sets, through: :game_match_set_relations 

class MatchSet < ActiveRecord::Base 
    has_many :game_match_set_relations 
    has_many :games, through: :game_match_set_relations 

class GameMatchSetRelation < ActiveRecord::Base 
    belongs_to :game 
    belongs_to :match_set 

    validates :game_id, presence: true 
    validates :match_set_id, presence: true 
+0

을 나는 조인을 생각하는 모델은, 내가 생각하는 – mechanicalfish

+0

@mechanicalfish 불필요 : 영업 이익이 게임 [...]'말했지만 그들은 많은에 속할 수 있습니다 Matchsets.' – MrYoshiji

+0

네, 모델이 없으니'has_and_belongs_to_many'. 물론 조인 테이블 자체가 필요합니다. – mechanicalfish