【问题标题】:Rails - Modeling Like ObjectsRails - 像对象一样建模
【发布时间】:2017-03-01 23:59:10
【问题描述】:

Rails 新手在这里。我正在尝试创建一个应用程序来显示有关足球比赛的信息。我有一个Game 模型,用于包含有关匹配的信息。我想在game 对象中包含的一种信息是比赛中发生的事件,例如进球和纪律处分。

class Game < ApplicationRecord
  has_many :events
end

模拟这些事件的最佳方法是什么?应该只有一个Event 模型,还是创建多个扩展Event 的模型(例如GoalYellowCardRedCard 等)有什么优势?

【问题讨论】:

    标签: ruby-on-rails oop model


    【解决方案1】:

    您可以使用类似 EventType 的模型:

    # game.rb
    class Game < ApplicationRecord
      has_many :events
    end
    
    # event.rb
    class Event < ApplicationRecord
      belongs_to :event_type
    end
    
    # event_type.rb
    class EventType < ApplicationRecord
    end
    

    events 表中,您可以存储时间/注释等信息,并且会有一个字段event_type_id。在event_types 表中,您可以存储诸如目标、黄牌等动作。

    然后您就可以轻松地进行查询,例如查找特定比赛中的所有目标等。

    【讨论】:

    • 没想到这个,但我喜欢这个主意。有没有什么好的方法来解释 event 对象需要依赖于它所属的 event_type 的不同属性?
    【解决方案2】:

    一个帮助您入门的建议。

    class Game < ActiveRecord::Base
      has_many :teams
      has_many :players, through: :teams
      has_many :goals
      has_many :cards
    end
    
    class Team < ActiveRecord::Base
      has_many :players
    end
    
    class Player < ActiveRecord::Base
      belongs_to :team
      has_many :cards
      has_many :goals
    end
    
    class Card < ActiveRecord::Base
      belongs_to :player
      belongs_to :game
    end
    
    class Goal < ActiveRecord::Base
      belongs_to :player
      belongs_to :game
    end
    

    *obs:您可能需要添加 TeamLineup 模型,因为团队可以根据游戏拥有不同的阵容。我知道您询问了事件,但我认为上面提出的解决方案可以更好地模拟足球比赛

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 2010-10-27
      • 1970-01-01
      • 2018-12-27
      • 2021-11-12
      • 1970-01-01
      相关资源
      最近更新 更多