How to describe this Ruby on Rails relationship

I have two classes in a Rails application. One of them Athlete, and the other - AthleteGameLog. An interesting part of this relationship is that for many years the athlete has has_manyspecimens AthleteGameLog. However, in the context of the current season, there Athleteshould be only one game magazine per year. So, one for 2013, one for 2014, etc.

When working with Ruby on Rails, is the relation has_manystill here - the right way to do this? Do I have to write scopeto get the right relationship for a particular year? Am I looking for all instances AthleteGameLog?

+3
source share
4 answers

A has_many . , , AthleteGameLog Athlete, .

, . - .

Athlete.game_log_for_year(2013) , .

+2

, . :

class AthleteGameLog < ActiveRecord::Base
  scope :for_year, ->(year) { find_by(year: year) }
end

athlete.game_logs.for_year(2014)

, , :

class AthleteGameLog < ActiveRecord::Base
  def self.for_year(year)
    scoped.find_by(year: year)
  end
end
+1

What about:

class Athlete < ActiveRecord::Base
  # columns: id, <athlete columns>
  has_many :athlete_game_logs
end

class AthleteGameLog < ActiveRecord::Base
  # columns: id, <gamelog columns>, year
  belongs_to :athlete
  validates :athlete_id, :uniqueness => { scope: :year }
end
0
source

It is enough to add a unique index or a unique restriction on athlete_id and year.

-1
source

All Articles