2013-11-14 85 views
3

我遇到了麻烦,我认为这是一个基本的关联。rails协会 - has_many vs has_and_belongs_to_many

我有一个游戏模型和一个Matchset模型。

在游戏模型是一个游戏列表。游戏只在游戏桌上列出一次,但它们可以属于许多比赛集。

matchset.rb -

has_many :games 

为game.rb我不知道我会放。我不想放置belongs_to,因为它属于许多比赛集,而不仅仅是一个。而且我认为我不想把has_and_belongs_to_many放在这里,因为matchsets不一定“属于”游戏,但也许我只是看错了。

实施例:Matchset 1具有游戏1,3和5 Matchset 2具有游戏2和3 Matchset 3具有游戏3,4和5

我在与Oracle SQL,在我的头背景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:在OP说'的游戏[...],但他们也可以属于多Matchsets.' – MrYoshiji

+0

是的,所以没有模型的'has_and_belongs_to_many'。连接表本身当然是需要的。 – mechanicalfish