简体   繁体   English

Rails多态关联has_many

[英]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 . 我想这样做的方法是创建一个整体的Stat模型,其中包含每个Stat的基本属性,而与运动无关,例如位置,日期,对手等。这样,每种运动都会从Stat模型,例如FootballStatBasketballStat

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: 因此,我只找到了两个其他选择:

  • Polymorphic association, and 多态关联,以及
  • Multiple Table Inheritance. 多表继承。

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! 谢谢!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM