【问题标题】:How to organize seasons in Clubs and Teams for Rails models?如何在俱乐部和团队中为 Rails 模型组织赛季?
【发布时间】:2014-02-04 08:38:28
【问题描述】:

我有以下情况:

我有一个可以有多个团队的俱乐部,而一个团队可以有多个玩家。

但是,球队拥有的球员每年都会有所不同。我想知道如何以某种方式将赛季信息放入图片中,以便用户能够在每个赛季添加/删除球员并能够看到前几个赛季的球队球员。

所以,给定以下模型:

Club has_many Team
Team belongs_to Club
Team has_many Players

我将如何使团队 has_many Players 取决于赛季(2013/2014 - 2012/2013..)

【问题讨论】:

    标签: ruby-on-rails database-design model


    【解决方案1】:

    有两种方法:

    一种是为SEASON创建另一个关系,并创建一个三元关系(http://www.databasedesign.co.uk/bookdatabasesafirstcourse/chap3/chap3.htm

    表格看起来像这样:

        PLAYER(id,...)
        TEAM(id,name,...,club_id)
        SEASON(id,season_name,...)
        SEASON_PARTICIPATION(id,player_id,season_id,team_id)
    

    ActiveRecord 关联将是:

        class Club < ActiveRecord::Base
          has_many :teams
        end
    
        class Team < ActiveRecord::Base
          belongs_to :club
          has_many :players, through: :season_participations
        end
    
        class Player < ActiveRecord::Base
          belongs_to :teams, through: :season_participations
        end
    
        class Season < ActiveRecord::Base
          has_many :players, through: :season_participations
        end
    
        class SeasonParticipation < ActiveRecord::Base
          belongs_to :player
          belongs_to :team
          belongs_to :season
        end
    

    更多关于ActiveRecord关联的文档可以在这里找到:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

    另一种方法是一起跳过SEASON 关系并将其作为SEASON_PARTICIPATION 关系中的简单属性。因此,您将在SEASON_PARTICIPATION 中使用季节名称而不是season_id(参见图表2)。拥有一个单独的SEASON 关系让您有机会存储有关赛季的更多信息,例如开始日期/结束日期等。最终,您还可以在另一个关系中添加部门信息。

    【讨论】:

      【解决方案2】:

      有很多方法可以做到这一点。这里有一些立即想到的春天。

      1. 在 Player 模型中添加一个赛季列。通过回调在创建时设置玩家的季节属性。如果 season != current_season,则阻止用户创建、更新或销毁播放器。
      2. 使用已在 Player 模型中提供的 updated_at 列执行基本相同的操作。创建一个方法来解析日期时间并将其转换为对您更有用的东西,可能是季节编号或类似的东西。

      【讨论】:

      • 这没关系,但如果您需要保留球员球队/俱乐部的历史记录,您将无法保留。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 2012-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多