多个has_many通过相同模型之间的关联

时间:2014-09-03 09:53:12

标签: ruby-on-rails has-many-through

我对用于记录足球(足球)比赛的铁路应用数据库的设计有一些疑问。统计

我有三种模式:

  • 匹配
  • 播放器
  • 目标

有以下关系:

  • 每场比赛都可以有主队球员的很多进球
  • 每场比赛可以有很多目标球员的进球
  • 每位球员(主场和观众队)都可以在比赛中打进很多球门

这是我的模特'结构:

class Match < ActiveRecord::Base
  has_many :home_goals,
       class_name: 'Goal',
       foreign_key: 'home_match_id'
  has_many :home_scorers,
       class_name: 'Player',
       foreign_key: 'home_scorer_id',
       through: :home_goals

  has_many :visitor_goals,
       class_name: 'Goal',
       foreign_key: 'visitor_match_id'
  has_many :visitor_scorers,
       class_name: 'Player',
       foreign_key: 'visitor_scorer_id',
       through: :visitor_goals

  ...

end


class Goal < ActiveRecord::Base
  belongs_to :home_match,
      class: 'Match',
      foreign_key: 'home_match_id'
  belongs_to :visitor_match,
      class: 'Match',
      foreign_key: 'visitor_match_id'

  belongs_to :player
end


class Player < ActiveRecord::Base
  has_many :goals
  has_many :home_matches,
      class_name: 'Match',
      foreign_key: 'home_scorer_id',
      through: :goals

  has_many :visitor_matches,
      class_name: 'Match',
      foreign_key: 'visitor_scorer_id',
      through: :goals

  ...

end
  1. 我可以嵌套&#34; has_many_through&#34;这种关系?

  2. 不寻常的是,一名球员可以在一场比赛中得分超过一个。因此,可能存在多个具有相同玩家和相同匹配的目标。 这可能会导致错误吗?

  3. 我的终极目标&#34;是能够计算所有比赛中球员得分的数量,获得每场比赛的主场球员,主场球员,观众球员和访客目标。有没有更好的方法来组织数据库?

1 个答案:

答案 0 :(得分:0)

看起来你需要像Polymorphic Association这样的东西。这基本上允许模型具有多个belongs_to rails文档具有良好的信息:http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

有了这个,目标可以属于玩家和比赛,并且可以让玩家has_many和匹配has_many更加干净。

相关问题