在Rails中建模游戏比赛的好方法? [英] Good Approach to modeling a Game Match in Rails?

查看:84
本文介绍了在Rails中建模游戏比赛的好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Rails中的匹配类型建立模型.比赛需要跟踪以下内容:

I'm trying to have a model for a type of match in Rails. the match needs to keep track of the following:

  • 两个球员
  • 获胜者

没有分数或类似的东西.我可以看到这样做是与玩家的3个独立的has_one关系,但是对我来说这似乎很不客气.有没有更好的方法来解决这个问题?

no scores or anything like that. I could see doing this as 3 separate has_one relations to the player, but that seems hacky to me. Is there a better way to approach this?

推荐答案

只有两个字段呢?

class GameMatch < ActiveRecord::Base

  belongs_to :winner, :class_name => 'Player'
  belongs_to :loser, :class_name => 'Player'

end

如果您需要在游戏完成之前将GameMatch输入系统,则必须具有三个字段,但是您也可以像下面这样详细说明它:

If you need to enter the GameMatch into the system before the game is completed, you'll have to have three fields, but you could alternatively detail it like this:

class GameMatch < ActiveRecord::Base

  belongs_to :home_player, :class_name => 'Player'
  belongs_to :away_player, :class_name => 'Player'

  def winner
    self[:home_won] ? home_player : away_player
  end      

  def winner=(player)
    self[:home_won] = player == home_player
  end

end

当然,您必须在其中进行一些处理,以确保获胜者能够参加比赛,并且不是决定要求胜利的围观者.

Granted, you'll have to have some handling in there to make sure the winner played the game and wasn't an onlooker that decided to claim the victory.

这篇关于在Rails中建模游戏比赛的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆