简体   繁体   中英

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.

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.

matchset.rb -

has_many :games

for game.rb I'm not sure what I would put. I don't want to put belongs_to because it belongs to many matchsets, not just one. 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.

Example: Matchset 1 has games 1, 3, and 5. Matchset 2 has games 2 and 3. Matchset 3 has games 3, 4, and 5.

My background in with Oracle SQL and in my head the Matchset table would look something like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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