导轨 - 像对象一样建模



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

class Game < ApplicationRecord
  has_many :events
end

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

您可以使用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表中,您可以存储诸如Time/Notes之类的信息,并且会有一个字段event_type_id。在event_types表中,您可以存储诸如目标,Yellow_card等的操作。

然后,您可以轻松地进行查询,例如在特定匹配中找到所有目标等。

一个建议让您入门。

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模型,因为团队可以根据游戏的不同阵容。我知道您询问了事件,但我认为上面提出的解决方案可以更好地建模

最新更新