Domanda

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.

È stato utile?

Soluzione

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top