randombits
randombits

Reputation: 48500

How to describe this Ruby on Rails relationship

I have two classes in my Rails application. One of them is Athlete and the other is AthleteGameLog. The interesting part of this relationship is that over the course of many years an athlete has_many instances of an AthleteGameLog. In the context of the current season however, the Athlete should have only one game log per year. So, one for 2013, one for 2014, etc.

When working with Ruby on Rails, is the has_many relationship still here the right way to go about this? Do I have to write a scope in order to retrieve the correct relationship for the specific year I am looking for all AthleteGameLog instances on?

Upvotes: 3

Views: 86

Answers (4)

Jacek
Jacek

Reputation: 412

It is worthy add some unique index or unique constraint on athlete_id and year.

Upvotes: -1

franksort
franksort

Reputation: 3153

How 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

Upvotes: 0

BroiSatse
BroiSatse

Reputation: 44725

Yes, it is definitively still has_many relationship. You can write parametrized scope to retrieve correct log:

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

athlete.game_logs.for_year(2014)

For those unhappy with scope not returning association proxy:

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

Upvotes: 1

jklina
jklina

Reputation: 3417

A has_many relationship sounds just fine. You might want to add a validation that only allows one AthleteGameLog per year per Athlete which wouldn't be too hard.

You could write a scope if you choose that takes a year as an input and returns the correct game log. Something like.

Athlete.game_log_for_year(2013) for example which will return the correct game log.

Upvotes: 2

Related Questions