Rails非常新,已经管理了一些简单的项目,但现在进入表之间更复杂的关联,并希望得到一些帮助。
该场景最适合体育比赛。假设我们有
1)一支球队(有很多球员)
2)玩家(belongs_to团队)
3)匹配 - 现在变得棘手。
比赛将有:2支队伍,22名队员(每侧11名)参加比赛。此外,与每位球员相关联的将是他们的比赛得分(例如,射门得分,进球得分,得分等)
创建这种关联的最佳做法是什么?任何提示将不胜感激。
答案 0 :(得分:0)
玩家拥有并属于多场比赛
该表应包含播放该匹配的玩家的详细信息。例如,他参加过哪支球队,从哪一分钟开始(因为球员可以改变)等等。
答案 1 :(得分:0)
应用程序/模型/ team.rb
class Team < ActiveRecord::Base
has_many :players, inverse_of: :team
has_many :team_matches
has_many :matches, through: :team_matches
end
应用程序/模型/ player.rb
class Player < ActiveRecord::Base
belongs_to :team, inverse_of: :player
has_many :player_matches
has_many :matches, through: :player_matches
end
应用程序/模型/ match.rb
class Match < ActiveRecord::Base
has_many :players, through: :player_matches
has_many :teams, through: :team_matches
end
应用程序/模型/ team_match.rb
class TeamMatch < ActiveRecord::Base
belongs_to :team
belongs_to :match
end
应用程序/模型/ player_match.rb
class PlayerMatch < ActiveRecord::Base
belongs_to :player
belongs_to :match
end
分贝/迁移/ create_matches.rb
class CreateMatches < ActiveRecord::Migration
def change
create_table :matches do |t|
t.datetime :happened_at
t.timestamps
end
end
end
分贝/迁移/ create_players.rb
class CreatePlayers < ActiveRecord::Migration
def change
create_table :players do |t|
t.string :name
t.timestamps
end
end
end
分贝/迁移/ create_teams.rb
class CreateTeams < ActiveRecord::Migration
def change
create_table :teams do |t|
t.string :name
t.timestamps
end
end
end
分贝/迁移/ create_player_matches.rb
class CreatePlayerMatches < ActiveRecord::Migration
def change
create_table :player_matches do |t|
t.integer :match_id
t.integer :player_id
t.integer :player_shots_on_goal
t.integer :player_goals_scored
t.timestamps
end
end
end
分贝/迁移/ create_team_matches.rb
class CreateTeamMatches < ActiveRecord::Migration
def change
create_table :team_matches do |t|
t.integer :match_id
t.integer :team_id
t.integer :team_points
t.timestamps
end
end
end
Edit1:@Mischa应该在这里分享信用! :)
Edit2:对很多版本感到抱歉,我完全低估了这个问题。