Jump to content

The ultimate community for Ruby on Rails developers.


Model Advice

  • Please log in to reply
1 reply to this topic

#1 grogers



  • Members
  • 1 posts

Posted 10 September 2013 - 11:05 AM

I need to setup models to store the results of athletic events.  I think this is fairly straightforward, but want to make sure I'm making the right decision at the outset.


I'm planning Athlete and Match models.  Each Match has just two Athletes.


Do I need anything more than a HABTM relationship?  Since there are only two athletes for any match, is there any sense in just storing both athlete_id's in the Match model directly?


In a HABTM, what's the cleanest code to query for matches played between two specific athletes?


Thanks in advance!



#2 Vito Botta

Vito Botta


  • Members
  • 13 posts
  • LocationEspoo, Finland

Posted 15 September 2013 - 08:23 PM

Will each match always have only two athletes? Generally speaking I wouldn't like adding both athlete ids in the Match model from a database design standpoint, so I'd prefer HABTM also because it gives you flexibility in the case a match can later have more than two athletes (could it be that later you may have different types of matches or something like that?)


If you go the HABTM route, you can find the matches played between two given athletes with something like this:

class Match < ActiveRecord::Base

  has_many :match_athletes
  has_many :athletes, through: :match_athletes


  def self.for_athletes(athlete1_id, athlete2_id)
      joins("INNER JOIN match_athletes ma1 ON ma1.match_id = matches.id").
      joins("INNER JOIN match_athletes ma2 ON ma2.match_id = matches.id").
      where("ma1.athlete_id = ? AND ma2.athlete_id = ?", athlete1_id, athlete2_id)

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users