Search code examples
ruby-on-railsdatabase-designassociationsmodels

Ruby On Rails Model Relationships and Associations


I have Two models named Rounds and Teams, Each round has 2 teams team 1 and team 2 and their respective scores like team_1_score and team_2_score. Team has many rounds. I am aware of how to tackle multiple associations using class and foreign keys from rounds table to Teams table. What's been confusing for me is, how to handle their respective scores. For example Is there any way to get 1st team score like first_team.rounds.where('some condition').score. Can I use such prototype to get first team score and if second team object is used then it returns second team score. I am looking forward for any sort of help. That would be really great. Thank you


Solution

  • You have your models

    class Round < ApplicationRecord
      has_many :teams
    end
    
    class Team < ApplicationRecord
      has_many :rounds
    end
    

    To get a specific teams score on a specific round I would do:

    @team = Team.find(id: params[:team_id])
    
    score =  Round.where(team_id: @team.id).team_1_score
    

    Assuming you do this in a controller where the params are present, otherwise just find the team and round by their id's and do

    I'd suggest you use a has_many :through relationship though. This would create a whole new table where you could query records by round ID and team ID and then return the teams score.