0

私は非常に単純なことを試みています。この時点で、次の 3 つのモデルがあります。

Player >> PlayerMatch >> Match

class Match < ActiveRecord::Base
  attr_accessible :date, :goals_team_a, :goals_team_b
  has_many :PlayerMatches
  has_many :Players, :through => :PlayerMatches
end

class Player < ActiveRecord::Base
  attr_accessible :name, :password_confirmation, :password, :user
  has_many :PlayerMatches
  has_many :matches, :through => :PlayerMatches
end

class PlayerMatch < ActiveRecord::Base
  attr_accessible :match_id, :player_id, :team
  belongs_to :player
  belongs_to :match
end

モデル PlayerMatch は結合エンティティです。プレーヤーがプレーする各試合で、チーム A またはチーム B に所属することができるため、PlayerMatch でその属性のチームを作成しました。

試合ごとに価値のあるチームを設定するにはどうすればよいですか? 私は次のようなことをしたい:

p = Player.new
//set players attributes
m = Match.new
//set match attributes

p.matches << m

今、私は彼のチームをその特定の試合に設定したいだけです.

前もって感謝します!

4

1 に答える 1

0

設定したモデルを使用して、次のようなことができます。

p = Player.create
m = Match.create
pm = PlayerMatch.create(:player => p, :match => m, :team => 'Team')

例のように PlayerMatch を自動的に作成する場合は、後でそれを取得して、その時点でチームを設定できます。

p = Player.create
m = Match.create
p.matches << m

pm = p.matches.where(:match_id => m.id).first
pm.update_attributes(:team => 'Team')

ただし、個々のプレーヤーが異なるチームで異なる試合をプレイできると言っている場合を除き、代わりにプレーヤーをチームに所属させたいと思うかもしれません。

この投稿には、この質問に関連する情報もあります。

于 2012-12-21T04:21:40.687 に答える