2016-05-06 4 views
0

私は2種類のモデル:GamePlayerを持っています。Railsモデルデザインの特別なメンバー

class Game < ActiveRecord::Base 
    has_many :players 
end 

class Player < ActiveRecord::Base 
    belongs_to :game 
end 

ゲームに属するすべてのプレイヤーのうち、1人のプレイヤーのみが開始プレーヤーです。

モデルとdbスキーマの設計方法を教えてください。

ゲームの開始プレーヤーは誰ですかについての情報は、Gameにあるだけでしょうか?

答えて

0

あなたはゲームは、常に1人の出発プレーヤーを持っていること、これは将来的には変わらないであろうことを確信している場合、あなたはケースの場合には、

class Game < ActiveRecord::Base 
    # has the following attributes 
    # starting_player_id:integer:index 

    belongs_to :starting_player, class: Player 
    has_many :players 
end 

class Player < ActiveRecord::Base 
    # has the following attributes 
    # game_id:integer:index 

    has_one :starting_game, foreign_key: :starting_player_id, class: Game 
    belongs_to :game 
end 

ただし、次の

のような関係を持つことができますPlayer-Gameは多対多で、私の答えを変更して別のテーブルに追加する必要があります

0

プレイヤーである人のチームについて話している場合は、すべてのプレイヤーとゲームプレイヤー。プレイヤーは時間の経過と共に行き来することができますが、どのプレイヤーがスタートプレイヤーであったか、どのプレイヤーがそのゲームにあったかなど、特定のものを定義することができます。

したがって、このような何か:

class Player < ActiveRecord::Base 
    has_many :game_players 
    has_many :games, through: :game_players 
end 


class Game < ActiveRecord::Base 
    has_many :game_players 
    has_many :players, through: :game_players 
end 

class GamePlayer < ActiveRecord::Base 
    belongs_to :game 
    belongs_to :player 

def starting_player 
    return GamePlayer.joins(:game).merge(GamePlayer.starting).first.player 
    end 
end 

のでGamePlayerだけ

game_id (an integer) 
player_id (an integer) 
starting (a boolean) 

次にあなたが

@game.starting_player 

を言うことができるだろうと、それは戻ってくる、いくつかのフィールドを持っているでしょう開始したシングルプレイヤー

チームスポーツの場合は、各プレーヤーにスタートプレーヤーがあるので、start_playerメソッドで「最初の」コールを削除する必要があります。これにより、2人のプレーヤーの配列が得られます。プレーヤーに関連するチームモデルもある場合は、両方のチームを獲得できます

@games.starting_player.each do |player| 
    # Whatever kind of formulations or front end view code you need 
    player.team.name 
end 
関連する問題