我正在建立一个棒球统计应用程序。我很难将游戏分成几个季节。
一场比赛有很多击球,投球和守门员。游戏还有一个playing_date字段,我可以从中获取年份。
基本上我想要做的就是能够将游戏分成季节,并在该季节内添加列。
例如,能够做到:
<% @player.each do |player| %>
<% player.battings.seasons.each do |battingseason| %>
<%= battingseason.total("homeruns") %>
<% end %>
<% end %>
所以“battingseason.total(”homeruns“)”将总结那个特定球员在那个赛季中击中的全部本垒打。
通过这个游戏,我能够获得多年的游戏:
@game_seasons = @games.group_by { |g| g.played_date.beginning_of_year }
......但我不确定它有多大的帮助。
从那里,我还需要能够将季节分为秋季和春季。例如,我目前拥有的东西:
def season
if self.game.played_date.month >= 9 && self.game.played_date.month <= 12
season = "fall"
else
season = "spring"
end
end
所以我的问题是我只是不确定在控制器中将所有这些逻辑放在模型中的哪个位置?如何输出它,谢谢!
答案 0 :(得分:0)
我会创建一个Season
模型。季节模型有一列season
。我会这样设置模型:
class Season < ActiveRecord::Base
has_many :games
has_many :battings, through: :games
has_many :pitchings, through: :games
has_many :fieldings, through: :games
end
class Game < ActiveRecord::Base
belongs_to :season
end
您需要将season_id
添加到games
表,然后在before_validate
模型中添加game
方法:
before_validate :find_or_create_season
private
def find_or_create_season
if self.played_date.month >= 9 && self.played_date.month <= 12
season = "fall"
else
season = "spring"
end
season_name = season + ' ' + self.played_date.year.to_s
game_season = Season.find_or_create_by_season(season_name)
self.season_id = game_season.id
end
我不确定你希望你的视图看起来像什么,但这是一种可能性。这将为您提供按季节为本垒打的一名球员的摘要:
在您的控制器中:
def show
@player = Player.find(params[:id])
#not sure how you define if a batting was a homerun. I assumed that you have a boolean for that
@homeruns_by_season = @player.battings.where('homerun = ?', true).group(:season).count
#this will return a hash with season as a key and the count as the value
end
在你看来
<% @homeruns_by_season.each do |season, homeruns| %>
<td><%= season.season %></td>
<td><%= homeruns %></td>
<% end %>