amb110395
amb110395

Reputation: 1545

Rails polymorphic association has_many

I want to create a sport statistic webpage where I can store different sport stats for each player. A player can have stats from different sports.

The way I was thinking of doing this is to create an overall Stat model that contains the basic attributes for every stat, regardless of the sport, such as place, date, opponent, etc. In this way, each sport that would inherit from the Stat model - such FootballStat and BasketballStat.

It seems that using Single Table Inheritance will prove to be very inefficient because every sport has very different statistics. Therefore, I only found two other options:

Which one do you think will be more effective in this case? And how would go about implementing it?


This is what I am trying to do, maybe you can please help me. Thank you!

Upvotes: 1

Views: 1380

Answers (1)

Super Engineer
Super Engineer

Reputation: 1976

Polymorphic associations is surely the way to go. You can implement it as follows.

Class Stat 
  belongs_to :sportable, 
  belongs_to :player
end

Class Sport1
  has_many :stats, :as => :sportable
  # various attributes for sport1
end

Class Sport2
  has_many :stats, :as => :sportable
  # various attributes for sport2
end

Class Player
  has_many :stats
end

Upvotes: 1

Related Questions