2017-03-05 81 views
2

我是Rails的一名初学者,但随时都在学习。我正在尝试创建一个锦标赛入场门户网站,一个球队可以进入参加锦标赛的选手。我已经完成了关于关联的一些阅读,但是在这种情况下如何应用它们会遇到一些麻烦。比赛 - >球队 - >球员协会

作为基本概述:

  • 一个比赛,有很多球队。
  • 每队有很多球员
  • 因此一个巡回赛也有不少玩家(通过团队
    进入)

这里是我这个代码,但我不知道这是正确的,因为我无法获得与玩家相关的任何tournament_ids。

(tournament.rb)

class Tournament < ApplicationRecord 
    has_many :teams 
    has_many :players, :through => :teams 
end 

(team.rb)

class Team < ApplicationRecord 
    belongs_to :tournament 
    has_many :players 
end 

(player.rb)

class Player < ApplicationRecord 
    has_one :team 
    has_one :tournament, :through => :team 
end 

内玩家桌子上有两个TEAM_ID & tournament_id字段,但是我只能通过关联来填充team_id字段,当我尝试使用CONSOL时即

我想知道是否有什么与我的协会不协调。

回答

0

'belongs_to','has_many','has_one'的用法当然取决于数据库中的数据模型。

如果您在players表TEAM_ID外键,那么您需要定义播放器类为:

class Player < ApplicationRecord 
    belongs_to :team 
    has_one :tournament, :through => :team 
end 

此外,我真的相信那场比赛< - >团队应该有很多-to-many关联(如果球队可以参加许多比赛当然)。我建议增加模型TeamTournament并确定最终的模型结构为:

class Tournament < ApplicationRecord 
    has_many :team_tournaments 
    has_many :teams, :through => :team_tournaments 
    has_many :players, :through => :teams 
end 

class TeamTournament < ApplicationRecord 
    belongs_to :team 
    belongs_to :tournament 
end 

class Team < ApplicationRecord 
    has_many :team_tournaments 
    has_many :tournaments, :through => :team_tournaments 
    has_many :players 
end 
+0

出于兴趣如何使用TeamTournament模型?我在这个地方的几个不同的答案和例子中看到了一个类似的概念,但我无法让我的头脑围绕使用/概念 - 可能缺乏经验。 – afishintaiwan

0

Player类应该有belongs_to的与Team和比赛

class Player < ApplicationRecord 
    belongs_to :team 
    belongs_to :tournament 
end 
+0

'belongs_to:tournament,:through =>:team'''将不起作用 –

+0

'belongs_to'在当前表上使用foreign_key。除非'参赛选手'表格包含对锦标赛的参考,否则锦标赛可以定义为'''has_one:锦标赛,通过:: team''' –

0

OK协会。我假设你的问题是关于你的模型协会,而不是如何建立关联从player得到tournament_id等等。所以我会尽力向您提供一些关于您的项目的建议,并且可以为其设置关联。

因为我得到了你的门户网站的想法...你想tournament有很多teamsteam有很多players。但是你想从player得到tournament_id。我相信你不想这样做,因为在现实生活中,锦标赛确实可能“拥有”一些球员,但每个球员都不必参加某个锦标赛。他可以参加很多比赛。所以你不需要为此设置关联。锦标赛和球队也是如此。但是由于球队拥有球员,他必须属于该球队。所以你需要关联。

结束语我的设置你的将是这样的:

(tournament.rb)

class Tournament < ActiveRecord::Base 
    has_many :teams 
end 

(team.rb)

class Team < ActiveRecord::Base 
    has_many :players 
end 

(player.rb)

class Player < ActiveRecord::Base 
    belongs_to :team 
end 

还有一个关于如何你可以得到tournament其中某些team参加无直接关联:

team = Team.first # just take some team 
Tournament.includes(:teams).where(teams: { id: team.id }) 

用同样的方法,你可以实现你的其他目标(拿到赛某些球员属于等等)。但是这种情况不需要关联。当对象与另一个概念相关时,需要关联。