简体   繁体   English

rails association - has_many vs has_and_belongs_to_many

[英]rails association - has_many vs has_and_belongs_to_many

I am having trouble with what I thought would be a basic association. 我遇到了我认为是基本关联的问题。

I have a Game model and a Matchset model. 我有一个游戏模型和一个Matchset模型。

In the Game model is a list of games. 在游戏模型中是一个游戏列表。 The games are only listed once on the games table but they can belong to many Matchsets. 游戏只在游戏桌上列出一次,但它们可以属于许多Matchsets。

matchset.rb - matchset.rb -

has_many :games

for game.rb I'm not sure what I would put. 对于game.rb我不确定我会放什么。 I don't want to put belongs_to because it belongs to many matchsets, not just one. 我不想把belongs_to放在一起,因为它属于许多匹配集,而不仅仅是一个。 And I don't think I would want to put has_and_belongs_to_many because matchsets shouldn't necessarily "belong to" games, but maybe I'm just looking at it wrong. 而且我认为我不想放置has_and_belongs_to_many,因为匹配集不一定“属于”游戏,但也许我只是看错了。

Example: Matchset 1 has games 1, 3, and 5. Matchset 2 has games 2 and 3. Matchset 3 has games 3, 4, and 5. 示例:Matchset 1具有游戏1,3和5. Matchset 2具有游戏2和3. Matchset 3具有游戏3,4和5。

My background in with Oracle SQL and in my head the Matchset table would look something like this. 我在Oracle SQL中的背景,在我的脑海中,Matchset表看起来像这样。

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

Any help is appreciated. 任何帮助表示赞赏。

These relations should work for you: 这些关系对你有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM